blob: 1b9ccee9dbee38dd42d7769f290245df7e511058 [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.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000512 for (FunctionDecl *Older = Old->getPreviousDecl();
513 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000514 if (!Older->getParamDecl(p)->hasDefaultArg())
515 break;
516
517 OldParam = Older->getParamDecl(p);
518 }
519
520 Diag(OldParam->getLocation(), diag::note_previous_definition)
521 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000522 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000523 // Merge the old default argument into the new parameter.
524 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000525 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000526 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000527 if (OldParam->hasUninstantiatedDefaultArg())
528 NewParam->setUninstantiatedDefaultArg(
529 OldParam->getUninstantiatedDefaultArg());
530 else
John McCalle61b02b2010-05-04 01:53:42 +0000531 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000532 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000533 if (New->getDescribedFunctionTemplate()) {
534 // Paragraph 4, quoted above, only applies to non-template functions.
535 Diag(NewParam->getLocation(),
536 diag::err_param_default_argument_template_redecl)
537 << NewParam->getDefaultArgRange();
538 Diag(Old->getLocation(), diag::note_template_prev_declaration)
539 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000540 } else if (New->getTemplateSpecializationKind()
541 != TSK_ImplicitInstantiation &&
542 New->getTemplateSpecializationKind() != TSK_Undeclared) {
543 // C++ [temp.expr.spec]p21:
544 // Default function arguments shall not be specified in a declaration
545 // or a definition for one of the following explicit specializations:
546 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000547 // - the explicit specialization of a member function template;
548 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000549 // template where the class template specialization to which the
550 // member function specialization belongs is implicitly
551 // instantiated.
552 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
553 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
554 << New->getDeclName()
555 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000556 } else if (New->getDeclContext()->isDependentContext()) {
557 // C++ [dcl.fct.default]p6 (DR217):
558 // Default arguments for a member function of a class template shall
559 // be specified on the initial declaration of the member function
560 // within the class template.
561 //
562 // Reading the tea leaves a bit in DR217 and its reference to DR205
563 // leads me to the conclusion that one cannot add default function
564 // arguments for an out-of-line definition of a member function of a
565 // dependent type.
566 int WhichKind = 2;
567 if (CXXRecordDecl *Record
568 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
569 if (Record->getDescribedClassTemplate())
570 WhichKind = 0;
571 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
572 WhichKind = 1;
573 else
574 WhichKind = 2;
575 }
576
577 Diag(NewParam->getLocation(),
578 diag::err_param_default_argument_member_template_redecl)
579 << WhichKind
580 << NewParam->getDefaultArgRange();
581 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000582 }
583 }
584
Richard Smith58c3cc12012-11-28 03:45:24 +0000585 // DR1344: If a default argument is added outside a class definition and that
586 // default argument makes the function a special member function, the program
587 // is ill-formed. This can only happen for constructors.
588 if (isa<CXXConstructorDecl>(New) &&
589 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
590 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
591 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
592 if (NewSM != OldSM) {
593 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
594 assert(NewParam->hasDefaultArg());
595 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
596 << NewParam->getDefaultArgRange() << NewSM;
597 Diag(Old->getLocation(), diag::note_previous_declaration);
598 }
599 }
600
David Majnemeree4f4022014-03-30 06:44:54 +0000601 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000602 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000604 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000605 if (New->isConstexpr() != Old->isConstexpr()) {
606 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
607 << New << New->isConstexpr();
608 Diag(Old->getLocation(), diag::note_previous_declaration);
609 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000610 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
611 // C++11 [dcl.fcn.spec]p4:
612 // If the definition of a function appears in a translation unit before its
613 // first declaration as inline, the program is ill-formed.
614 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
615 Diag(Def->getLocation(), diag::note_previous_definition);
616 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000617 }
618
David Majnemer502b0ed2013-06-25 23:09:30 +0000619 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000620 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000621 // the only declaration of the function or function template in the
622 // translation unit.
623 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
624 functionDeclHasDefaultArgument(Old)) {
625 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
626 Diag(Old->getLocation(), diag::note_previous_declaration);
627 Invalid = true;
628 }
629
Douglas Gregorf40863c2010-02-12 07:32:17 +0000630 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000631 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000632
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000633 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000634}
635
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000636/// \brief Merge the exception specifications of two variable declarations.
637///
638/// This is called when there's a redeclaration of a VarDecl. The function
639/// checks if the redeclaration might have an exception specification and
640/// validates compatibility and merges the specs if necessary.
641void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
642 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000643 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000644 return;
645
646 assert(Context.hasSameType(New->getType(), Old->getType()) &&
647 "Should only be called if types are otherwise the same.");
648
649 QualType NewType = New->getType();
650 QualType OldType = Old->getType();
651
652 // We're only interested in pointers and references to functions, as well
653 // as pointers to member functions.
654 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
655 NewType = R->getPointeeType();
656 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
657 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
658 NewType = P->getPointeeType();
659 OldType = OldType->getAs<PointerType>()->getPointeeType();
660 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
661 NewType = M->getPointeeType();
662 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
663 }
664
665 if (!NewType->isFunctionProtoType())
666 return;
667
668 // There's lots of special cases for functions. For function pointers, system
669 // libraries are hopefully not as broken so that we don't need these
670 // workarounds.
671 if (CheckEquivalentExceptionSpec(
672 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
673 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
674 New->setInvalidDecl();
675 }
676}
677
Chris Lattner199abbc2008-04-08 05:04:30 +0000678/// CheckCXXDefaultArguments - Verify that the default arguments for a
679/// function declaration are well-formed according to C++
680/// [dcl.fct.default].
681void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
682 unsigned NumParams = FD->getNumParams();
683 unsigned p;
684
685 // Find first parameter with a default argument
686 for (p = 0; p < NumParams; ++p) {
687 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000688 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000689 break;
690 }
691
692 // C++ [dcl.fct.default]p4:
693 // In a given function declaration, all parameters
694 // subsequent to a parameter with a default argument shall
695 // have default arguments supplied in this or previous
696 // declarations. A default argument shall not be redefined
697 // by a later declaration (not even to the same value).
698 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000699 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000701 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000702 if (Param->isInvalidDecl())
703 /* We already complained about this parameter. */;
704 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000705 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000706 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000707 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000708 else
Mike Stump11289f42009-09-09 15:08:12 +0000709 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000711
Chris Lattner199abbc2008-04-08 05:04:30 +0000712 LastMissingDefaultArg = p;
713 }
714 }
715
716 if (LastMissingDefaultArg > 0) {
717 // Some default arguments were missing. Clear out all of the
718 // default arguments up to (and including) the last missing
719 // default argument, so that we leave the function parameters
720 // in a semantically valid state.
721 for (p = 0; p <= LastMissingDefaultArg; ++p) {
722 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000723 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000725 }
726 }
727 }
728}
Douglas Gregor556877c2008-04-13 21:30:24 +0000729
Richard Smitheb3c10c2011-10-01 02:31:28 +0000730// CheckConstexprParameterTypes - Check whether a function's parameter types
731// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000732// diagnostic and return false.
733static bool CheckConstexprParameterTypes(Sema &SemaRef,
734 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 unsigned ArgIndex = 0;
736 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000737 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
738 e = FT->param_type_end();
739 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000740 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
741 SourceLocation ParamLoc = PD->getLocation();
742 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000743 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000744 diag::err_constexpr_non_literal_param,
745 ArgIndex+1, PD->getSourceRange(),
746 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000747 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000748 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 return true;
750}
751
752/// \brief Get diagnostic %select index for tag kind for
753/// record diagnostic message.
754/// WARNING: Indexes apply to particular diagnostics only!
755///
756/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000757static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000758 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000759 case TTK_Struct: return 0;
760 case TTK_Interface: return 1;
761 case TTK_Class: return 2;
762 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000763 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000764}
765
766// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
767// the requirements of a constexpr function definition or a constexpr
768// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000769// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000770//
Richard Smith3607ffe2012-02-13 03:54:03 +0000771// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
772bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000773 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
774 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000775 // C++11 [dcl.constexpr]p4:
776 // The definition of a constexpr constructor shall satisfy the following
777 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000779 const CXXRecordDecl *RD = MD->getParent();
780 if (RD->getNumVBases()) {
781 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
782 << isa<CXXConstructorDecl>(NewFD)
783 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000784 for (const auto &I : RD->vbases())
785 Diag(I.getLocStart(),
786 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787 return false;
788 }
Richard Smith7971b692012-01-13 04:54:00 +0000789 }
790
791 if (!isa<CXXConstructorDecl>(NewFD)) {
792 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793 // The definition of a constexpr function shall satisfy the following
794 // constraints:
795 // - it shall not be virtual;
796 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
797 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000798 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 // If it's not obvious why this function is virtual, find an overridden
801 // function which uses the 'virtual' keyword.
802 const CXXMethodDecl *WrittenVirtual = Method;
803 while (!WrittenVirtual->isVirtualAsWritten())
804 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
805 if (WrittenVirtual != Method)
806 Diag(WrittenVirtual->getLocation(),
807 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 return false;
809 }
810
811 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000812 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000813 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000814 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000815 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817 }
818
Richard Smith7971b692012-01-13 04:54:00 +0000819 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000820 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000821 return false;
822
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823 return true;
824}
825
826/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000827/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000828///
Richard Smithd9f663b2013-04-22 15:31:51 +0000829/// \return true if the body is OK (maybe only as an extension), false if we
830/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000832 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
833 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000834 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
835 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000836 for (const auto *DclIt : DS->decls()) {
837 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000838 case Decl::StaticAssert:
839 case Decl::Using:
840 case Decl::UsingShadow:
841 case Decl::UsingDirective:
842 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000843 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000844 // - static_assert-declarations
845 // - using-declarations,
846 // - using-directives,
847 continue;
848
849 case Decl::Typedef:
850 case Decl::TypeAlias: {
851 // - typedef declarations and alias-declarations that do not define
852 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000853 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000854 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
855 // Don't allow variably-modified types in constexpr functions.
856 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
857 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
858 << TL.getSourceRange() << TL.getType()
859 << isa<CXXConstructorDecl>(Dcl);
860 return false;
861 }
862 continue;
863 }
864
865 case Decl::Enum:
866 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000867 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000868 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000869 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000870 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000871 ? diag::warn_cxx11_compat_constexpr_type_definition
872 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000873 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000874 continue;
875
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 case Decl::EnumConstant:
877 case Decl::IndirectField:
878 case Decl::ParmVar:
879 // These can only appear with other declarations which are banned in
880 // C++11 and permitted in C++1y, so ignore them.
881 continue;
882
883 case Decl::Var: {
884 // C++1y [dcl.constexpr]p3 allows anything except:
885 // a definition of a variable of non-literal type or of static or
886 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000887 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000888 if (VD->isThisDeclarationADefinition()) {
889 if (VD->isStaticLocal()) {
890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_static)
892 << isa<CXXConstructorDecl>(Dcl)
893 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
894 return false;
895 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000896 if (!VD->getType()->isDependentType() &&
897 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000898 VD->getLocation(), VD->getType(),
899 diag::err_constexpr_local_var_non_literal_type,
900 isa<CXXConstructorDecl>(Dcl)))
901 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000902 if (!VD->getType()->isDependentType() &&
903 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000904 SemaRef.Diag(VD->getLocation(),
905 diag::err_constexpr_local_var_no_init)
906 << isa<CXXConstructorDecl>(Dcl);
907 return false;
908 }
909 }
910 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000911 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000912 ? diag::warn_cxx11_compat_constexpr_local_var
913 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000914 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000915 continue;
916 }
917
918 case Decl::NamespaceAlias:
919 case Decl::Function:
920 // These are disallowed in C++11 and permitted in C++1y. Allow them
921 // everywhere as an extension.
922 if (!Cxx1yLoc.isValid())
923 Cxx1yLoc = DS->getLocStart();
924 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000925
926 default:
927 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931 }
932
933 return true;
934}
935
936/// Check that the given field is initialized within a constexpr constructor.
937///
938/// \param Dcl The constexpr constructor being checked.
939/// \param Field The field being checked. This may be a member of an anonymous
940/// struct or union nested within the class being checked.
941/// \param Inits All declarations, including anonymous struct/union members and
942/// indirect members, for which any initialization was provided.
943/// \param Diagnosed Set to true if an error is produced.
944static void CheckConstexprCtorInitializer(Sema &SemaRef,
945 const FunctionDecl *Dcl,
946 FieldDecl *Field,
947 llvm::SmallSet<Decl*, 16> &Inits,
948 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000949 if (Field->isInvalidDecl())
950 return;
951
Douglas Gregor556e5862011-10-10 17:22:13 +0000952 if (Field->isUnnamedBitfield())
953 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000954
Richard Smithab44d5b2013-12-10 08:25:00 +0000955 // Anonymous unions with no variant members and empty anonymous structs do not
956 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
957 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000958 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000959 (Field->getType()->isUnionType()
960 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
961 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000962 return;
963
Richard Smitheb3c10c2011-10-01 02:31:28 +0000964 if (!Inits.count(Field)) {
965 if (!Diagnosed) {
966 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
967 Diagnosed = true;
968 }
969 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
970 } else if (Field->isAnonymousStructOrUnion()) {
971 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000972 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000973 // If an anonymous union contains an anonymous struct of which any member
974 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000975 if (!RD->isUnion() || Inits.count(I))
976 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000977 }
978}
979
Richard Smithd9f663b2013-04-22 15:31:51 +0000980/// Check the provided statement is allowed in a constexpr function
981/// definition.
982static bool
983CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000984 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000985 SourceLocation &Cxx1yLoc) {
986 // - its function-body shall be [...] a compound-statement that contains only
987 switch (S->getStmtClass()) {
988 case Stmt::NullStmtClass:
989 // - null statements,
990 return true;
991
992 case Stmt::DeclStmtClass:
993 // - static_assert-declarations
994 // - using-declarations,
995 // - using-directives,
996 // - typedef declarations and alias-declarations that do not define
997 // classes or enumerations,
998 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
999 return false;
1000 return true;
1001
1002 case Stmt::ReturnStmtClass:
1003 // - and exactly one return statement;
1004 if (isa<CXXConstructorDecl>(Dcl)) {
1005 // C++1y allows return statements in constexpr constructors.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009 }
1010
1011 ReturnStmts.push_back(S->getLocStart());
1012 return true;
1013
1014 case Stmt::CompoundStmtClass: {
1015 // C++1y allows compound-statements.
1016 if (!Cxx1yLoc.isValid())
1017 Cxx1yLoc = S->getLocStart();
1018
1019 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001020 for (auto *BodyIt : CompStmt->body()) {
1021 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001022 Cxx1yLoc))
1023 return false;
1024 }
1025 return true;
1026 }
1027
1028 case Stmt::AttributedStmtClass:
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 return true;
1032
1033 case Stmt::IfStmtClass: {
1034 // C++1y allows if-statements.
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037
1038 IfStmt *If = cast<IfStmt>(S);
1039 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 if (If->getElse() &&
1043 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1044 Cxx1yLoc))
1045 return false;
1046 return true;
1047 }
1048
1049 case Stmt::WhileStmtClass:
1050 case Stmt::DoStmtClass:
1051 case Stmt::ForStmtClass:
1052 case Stmt::CXXForRangeStmtClass:
1053 case Stmt::ContinueStmtClass:
1054 // C++1y allows all of these. We don't allow them as extensions in C++11,
1055 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001056 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 break;
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 case Stmt::SwitchStmtClass:
1068 case Stmt::CaseStmtClass:
1069 case Stmt::DefaultStmtClass:
1070 case Stmt::BreakStmtClass:
1071 // C++1y allows switch-statements, and since they don't need variable
1072 // mutation, we can reasonably allow them in C++11 as an extension.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 for (Stmt::child_range Children = S->children(); Children; ++Children)
1076 if (*Children &&
1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1078 Cxx1yLoc))
1079 return false;
1080 return true;
1081
1082 default:
1083 if (!isa<Expr>(S))
1084 break;
1085
1086 // C++1y allows expression-statements.
1087 if (!Cxx1yLoc.isValid())
1088 Cxx1yLoc = S->getLocStart();
1089 return true;
1090 }
1091
1092 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1093 << isa<CXXConstructorDecl>(Dcl);
1094 return false;
1095}
1096
Richard Smitheb3c10c2011-10-01 02:31:28 +00001097/// Check the body for the given constexpr function declaration only contains
1098/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1099///
1100/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001101bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001102 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001103 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 // The definition of a constexpr function shall satisfy the following
1105 // constraints: [...]
1106 // - its function-body shall be = delete, = default, or a
1107 // compound-statement
1108 //
Richard Smith74388b42012-02-04 00:33:54 +00001109 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001110 // In the definition of a constexpr constructor, [...]
1111 // - its function-body shall not be a function-try-block;
1112 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1113 << isa<CXXConstructorDecl>(Dcl);
1114 return false;
1115 }
1116
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001117 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001118
1119 // - its function-body shall be [...] a compound-statement that contains only
1120 // [... list of cases ...]
1121 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1122 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001123 for (auto *BodyIt : CompBody->body()) {
1124 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001126 }
1127
Richard Smithd9f663b2013-04-22 15:31:51 +00001128 if (Cxx1yLoc.isValid())
1129 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001130 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001131 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1132 : diag::ext_constexpr_body_invalid_stmt)
1133 << isa<CXXConstructorDecl>(Dcl);
1134
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 if (const CXXConstructorDecl *Constructor
1136 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1137 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001138 // DR1359:
1139 // - every non-variant non-static data member and base class sub-object
1140 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001141 // DR1460:
1142 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001143 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001145 if (Constructor->getNumCtorInitializers() == 0 &&
1146 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1148 return false;
1149 }
Richard Smithf368fb42011-10-10 16:38:04 +00001150 } else if (!Constructor->isDependentContext() &&
1151 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001152 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1153
1154 // Skip detailed checking if we have enough initializers, and we would
1155 // allow at most one initializer per member.
1156 bool AnyAnonStructUnionMembers = false;
1157 unsigned Fields = 0;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001160 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001161 AnyAnonStructUnionMembers = true;
1162 break;
1163 }
1164 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001165 // DR1460:
1166 // - if the class is a union-like class, but is not a union, for each of
1167 // its anonymous union members having variant members, exactly one of
1168 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001169 if (AnyAnonStructUnionMembers ||
1170 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1171 // Check initialization of non-static data members. Base classes are
1172 // always initialized so do not need to be checked. Dependent bases
1173 // might not have initializers in the member initializer list.
1174 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001175 for (const auto *I: Constructor->inits()) {
1176 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001178 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 Inits.insert(ID->chain_begin(), ID->chain_end());
1180 }
1181
1182 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001183 for (auto *I : RD->fields())
1184 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001185 if (Diagnosed)
1186 return false;
1187 }
1188 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001189 } else {
1190 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001191 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001192 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001193 // otherwise if there's no return statement, the function cannot
1194 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001195 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001196 (Dcl->getReturnType()->isVoidType() ||
1197 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001198 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001199 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1200 : diag::err_constexpr_body_no_return);
1201 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 }
1203 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001204 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001205 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001206 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1207 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001208 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1209 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001210 }
1211 }
1212
Richard Smith74388b42012-02-04 00:33:54 +00001213 // C++11 [dcl.constexpr]p5:
1214 // if no function argument values exist such that the function invocation
1215 // substitution would produce a constant expression, the program is
1216 // ill-formed; no diagnostic required.
1217 // C++11 [dcl.constexpr]p3:
1218 // - every constructor call and implicit conversion used in initializing the
1219 // return value shall be one of those allowed in a constant expression.
1220 // C++11 [dcl.constexpr]p4:
1221 // - every constructor involved in initializing non-static data members and
1222 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001223 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001224 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001225 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001226 << isa<CXXConstructorDecl>(Dcl);
1227 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1228 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001229 // Don't return false here: we allow this for compatibility in
1230 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001231 }
1232
Richard Smitheb3c10c2011-10-01 02:31:28 +00001233 return true;
1234}
1235
Douglas Gregor61956c42008-10-31 09:07:45 +00001236/// isCurrentClassName - Determine whether the identifier II is the
1237/// name of the class type currently being defined. In the case of
1238/// nested classes, this will only return true if II is the name of
1239/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001240bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1241 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001242 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001243
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001244 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001245 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001246 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001247 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1248 } else
1249 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1250
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001251 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001252 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001253 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001254}
1255
Richard Smithfb8b7b92013-10-15 00:00:26 +00001256/// \brief Determine whether the identifier II is a typo for the name of
1257/// the class type currently being defined. If so, update it to the identifier
1258/// that should have been used.
1259bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1260 assert(getLangOpts().CPlusPlus && "No class names in C!");
1261
1262 if (!getLangOpts().SpellChecking)
1263 return false;
1264
1265 CXXRecordDecl *CurDecl;
1266 if (SS && SS->isSet() && !SS->isInvalid()) {
1267 DeclContext *DC = computeDeclContext(*SS, true);
1268 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1269 } else
1270 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1271
1272 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1273 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1274 < II->getLength()) {
1275 II = CurDecl->getIdentifier();
1276 return true;
1277 }
1278
1279 return false;
1280}
1281
Douglas Gregordc974572012-11-10 07:24:09 +00001282/// \brief Determine whether the given class is a base class of the given
1283/// class, including looking at dependent bases.
1284static bool findCircularInheritance(const CXXRecordDecl *Class,
1285 const CXXRecordDecl *Current) {
1286 SmallVector<const CXXRecordDecl*, 8> Queue;
1287
1288 Class = Class->getCanonicalDecl();
1289 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001290 for (const auto &I : Current->bases()) {
1291 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001292 if (!Base)
1293 continue;
1294
1295 Base = Base->getDefinition();
1296 if (!Base)
1297 continue;
1298
1299 if (Base->getCanonicalDecl() == Class)
1300 return true;
1301
1302 Queue.push_back(Base);
1303 }
1304
1305 if (Queue.empty())
1306 return false;
1307
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001308 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001309 }
1310
1311 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001312}
1313
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001314/// \brief Perform propagation of DLL attributes from a derived class to a
1315/// templated base class for MS compatibility.
1316static void propagateDLLAttrToBaseClassTemplate(
1317 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1318 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1319 if (getDLLAttr(
1320 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1321 // If the base class template has a DLL attribute, don't try to change it.
1322 return;
1323 }
1324
1325 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1326 // If the base class is not already specialized, we can do the propagation.
1327 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1328 NewAttr->setInherited(true);
1329 BaseTemplateSpec->addAttr(NewAttr);
1330 return;
1331 }
1332
1333 bool DifferentAttribute = false;
1334 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1335 if (!SpecializationAttr->isInherited()) {
1336 // The template has previously been specialized or instantiated with an
1337 // explicit attribute. We should not try to change it.
1338 return;
1339 }
1340 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1341 // The specialization already has the right attribute.
1342 return;
1343 }
1344 DifferentAttribute = true;
1345 }
1346
1347 // The template was previously instantiated or explicitly specialized without
1348 // a dll attribute, or the template was previously instantiated with a
1349 // different inherited attribute. It's too late for us to change the
1350 // attribute, so warn that this is unsupported.
1351 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1352 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1353 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1354 if (BaseTemplateSpec->isExplicitSpecialization()) {
1355 S.Diag(BaseTemplateSpec->getLocation(),
1356 diag::note_template_class_explicit_specialization_was_here)
1357 << BaseTemplateSpec;
1358 } else {
1359 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1360 diag::note_template_class_instantiation_was_here)
1361 << BaseTemplateSpec;
1362 }
1363}
1364
Mike Stump11289f42009-09-09 15:08:12 +00001365/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001366///
1367/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1368/// and returns NULL otherwise.
1369CXXBaseSpecifier *
1370Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1371 SourceRange SpecifierRange,
1372 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001373 TypeSourceInfo *TInfo,
1374 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001375 QualType BaseType = TInfo->getType();
1376
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 // C++ [class.union]p1:
1378 // A union shall not have base classes.
1379 if (Class->isUnion()) {
1380 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1381 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001382 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001383 }
1384
Douglas Gregor752a5952011-01-03 22:36:02 +00001385 if (EllipsisLoc.isValid() &&
1386 !TInfo->getType()->containsUnexpandedParameterPack()) {
1387 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1388 << TInfo->getTypeLoc().getSourceRange();
1389 EllipsisLoc = SourceLocation();
1390 }
Douglas Gregor62004702012-11-10 01:18:17 +00001391
1392 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1393
1394 if (BaseType->isDependentType()) {
1395 // Make sure that we don't have circular inheritance among our dependent
1396 // bases. For non-dependent bases, the check for completeness below handles
1397 // this.
1398 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1399 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1400 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001401 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001402 Diag(BaseLoc, diag::err_circular_inheritance)
1403 << BaseType << Context.getTypeDeclType(Class);
1404
1405 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1406 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1407 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001408
1409 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001410 }
1411 }
1412
Mike Stump11289f42009-09-09 15:08:12 +00001413 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001414 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001416 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001417
1418 // Base specifiers must be record types.
1419 if (!BaseType->isRecordType()) {
1420 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001421 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001422 }
1423
1424 // C++ [class.union]p1:
1425 // A union shall not be used as a base class.
1426 if (BaseType->isUnionType()) {
1427 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001428 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001429 }
1430
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001431 // For the MS ABI, propagate DLL attributes to base class templates.
1432 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1433 if (Attr *ClassAttr = getDLLAttr(Class)) {
1434 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1435 BaseType->getAsCXXRecordDecl())) {
1436 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1437 BaseTemplate, BaseLoc);
1438 }
1439 }
1440 }
1441
Douglas Gregor463421d2009-03-03 04:44:36 +00001442 // C++ [class.derived]p2:
1443 // The class-name in a base-specifier shall not be an incompletely
1444 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001445 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001446 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001447 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001448 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001449 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001450
Eli Friedmanc96d4962009-08-15 21:55:26 +00001451 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001452 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001453 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001454 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001455 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001456 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001457 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001458
David Majnemer9b1754d2013-11-02 12:00:36 +00001459 // A class which contains a flexible array member is not suitable for use as a
1460 // base class:
1461 // - If the layout determines that a base comes before another base,
1462 // the flexible array member would index into the subsequent base.
1463 // - If the layout determines that base comes before the derived class,
1464 // the flexible array member would index into the derived class.
1465 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1466 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1467 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001469 }
1470
Anders Carlsson65c76d32011-03-25 14:55:14 +00001471 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001472 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001473 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001474 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001475 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001476 << CXXBaseDecl->getDeclName()
1477 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001478 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1479 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001480 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001481 }
1482
John McCall3696dcb2010-08-17 07:23:57 +00001483 if (BaseDecl->isInvalidDecl())
1484 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001485
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001486 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001489 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001490}
1491
Douglas Gregor556877c2008-04-13 21:30:24 +00001492/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1493/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001494/// example:
1495/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001496/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001497BaseResult
John McCall48871652010-08-21 09:40:31 +00001498Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001499 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001500 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001501 ParsedType basetype, SourceLocation BaseLoc,
1502 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001503 if (!classdecl)
1504 return true;
1505
Douglas Gregorc40290e2009-03-09 23:48:35 +00001506 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001507 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001508 if (!Class)
1509 return true;
1510
David Majnemer5ef4fe72014-06-13 06:43:46 +00001511 // We haven't yet attached the base specifiers.
1512 Class->setIsParsingBaseSpecifiers();
1513
Richard Smith4c96e992013-02-19 23:47:15 +00001514 // We do not support any C++11 attributes on base-specifiers yet.
1515 // Diagnose any attributes we see.
1516 if (!Attributes.empty()) {
1517 for (AttributeList *Attr = Attributes.getList(); Attr;
1518 Attr = Attr->getNext()) {
1519 if (Attr->isInvalid() ||
1520 Attr->getKind() == AttributeList::IgnoredAttribute)
1521 continue;
1522 Diag(Attr->getLoc(),
1523 Attr->getKind() == AttributeList::UnknownAttribute
1524 ? diag::warn_unknown_attribute_ignored
1525 : diag::err_base_specifier_attribute)
1526 << Attr->getName();
1527 }
1528 }
1529
Craig Topperc3ec1492014-05-26 06:22:03 +00001530 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001531 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001532
Douglas Gregor752a5952011-01-03 22:36:02 +00001533 if (EllipsisLoc.isInvalid() &&
1534 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001535 UPPC_BaseType))
1536 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001537
Douglas Gregor463421d2009-03-03 04:44:36 +00001538 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001539 Virtual, Access, TInfo,
1540 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001541 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001542 else
1543 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001544
Douglas Gregor463421d2009-03-03 04:44:36 +00001545 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001546}
Douglas Gregor556877c2008-04-13 21:30:24 +00001547
Nathan Sidwell44b21742015-01-19 01:44:02 +00001548/// Use small set to collect indirect bases. As this is only used
1549/// locally, there's no need to abstract the small size parameter.
1550typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1551
1552/// \brief Recursively add the bases of Type. Don't add Type itself.
1553static void
1554NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1555 const QualType &Type)
1556{
1557 // Even though the incoming type is a base, it might not be
1558 // a class -- it could be a template parm, for instance.
1559 if (auto Rec = Type->getAs<RecordType>()) {
1560 auto Decl = Rec->getAsCXXRecordDecl();
1561
1562 // Iterate over its bases.
1563 for (const auto &BaseSpec : Decl->bases()) {
1564 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1565 .getUnqualifiedType();
1566 if (Set.insert(Base).second)
1567 // If we've not already seen it, recurse.
1568 NoteIndirectBases(Context, Set, Base);
1569 }
1570 }
1571}
1572
Douglas Gregor463421d2009-03-03 04:44:36 +00001573/// \brief Performs the actual work of attaching the given base class
1574/// specifiers to a C++ class.
1575bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1576 unsigned NumBases) {
1577 if (NumBases == 0)
1578 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001579
1580 // Used to keep track of which base types we have already seen, so
1581 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001582 // that the key is always the unqualified canonical type of the base
1583 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001584 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1585
Nathan Sidwell44b21742015-01-19 01:44:02 +00001586 // Used to track indirect bases so we can see if a direct base is
1587 // ambiguous.
1588 IndirectBaseSet IndirectBaseTypes;
1589
Douglas Gregor29a92472008-10-22 17:49:05 +00001590 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001591 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001592 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001593 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001594 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001595 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001596 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001597
1598 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1599 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001600 // C++ [class.mi]p3:
1601 // A class shall not be specified as a direct base class of a
1602 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001603 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001604 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001605 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001606 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001607
1608 // Delete the duplicate base class specifier; we're going to
1609 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001610 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001611
1612 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001613 } else {
1614 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001615 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001616 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001617
1618 // Note this base's direct & indirect bases, if there could be ambiguity.
1619 if (NumBases > 1)
1620 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1621
John McCalldb632ac2012-09-25 07:32:39 +00001622 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1623 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1624 if (Class->isInterface() &&
1625 (!RD->isInterface() ||
1626 KnownBase->getAccessSpecifier() != AS_public)) {
1627 // The Microsoft extension __interface does not permit bases that
1628 // are not themselves public interfaces.
1629 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1630 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1631 << RD->getSourceRange();
1632 Invalid = true;
1633 }
1634 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001635 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001636 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001637 }
1638 }
1639
1640 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001641 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001642
1643 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1644 // Check whether this direct base is inaccessible due to ambiguity.
1645 QualType BaseType = Bases[idx]->getType();
1646 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1647 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001648
Nathan Sidwell44b21742015-01-19 01:44:02 +00001649 if (IndirectBaseTypes.count(CanonicalBase)) {
1650 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1651 /*DetectVirtual=*/true);
1652 bool found
1653 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1654 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001655 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001656
1657 if (Paths.isAmbiguous(CanonicalBase))
1658 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1659 << BaseType << getAmbiguousPathsDisplayString(Paths)
1660 << Bases[idx]->getSourceRange();
1661 else
1662 assert(Bases[idx]->isVirtual());
1663 }
1664
1665 // Delete the base class specifier, since its data has been copied
1666 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001667 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001668 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001669
1670 return Invalid;
1671}
1672
1673/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1674/// class, after checking whether there are any duplicate base
1675/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001676void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001677 unsigned NumBases) {
1678 if (!ClassDecl || !Bases || !NumBases)
1679 return;
1680
1681 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001682 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001683}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001684
Douglas Gregor36d1b142009-10-06 17:59:45 +00001685/// \brief Determine whether the type \p Derived is a C++ class that is
1686/// derived from the type \p Base.
1687bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001688 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001689 return false;
John McCalle78aac42010-03-10 03:28:59 +00001690
Douglas Gregor45bb4832013-03-26 23:36:30 +00001691 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001692 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693 return false;
1694
Douglas Gregor45bb4832013-03-26 23:36:30 +00001695 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001696 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001698
1699 // If either the base or the derived type is invalid, don't try to
1700 // check whether one is derived from the other.
1701 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1702 return false;
1703
John McCall67da35c2010-02-04 22:26:26 +00001704 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1705 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706}
1707
1708/// \brief Determine whether the type \p Derived is a C++ class that is
1709/// derived from the type \p Base.
1710bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001711 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001712 return false;
1713
Douglas Gregor45bb4832013-03-26 23:36:30 +00001714 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001715 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001716 return false;
1717
Douglas Gregor45bb4832013-03-26 23:36:30 +00001718 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001719 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001720 return false;
1721
Douglas Gregor36d1b142009-10-06 17:59:45 +00001722 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1723}
1724
Anders Carlssona70cff62010-04-24 19:06:50 +00001725void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001726 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001727 assert(BasePathArray.empty() && "Base path array must be empty!");
1728 assert(Paths.isRecordingPaths() && "Must record paths!");
1729
1730 const CXXBasePath &Path = Paths.front();
1731
1732 // We first go backward and check if we have a virtual base.
1733 // FIXME: It would be better if CXXBasePath had the base specifier for
1734 // the nearest virtual base.
1735 unsigned Start = 0;
1736 for (unsigned I = Path.size(); I != 0; --I) {
1737 if (Path[I - 1].Base->isVirtual()) {
1738 Start = I - 1;
1739 break;
1740 }
1741 }
1742
1743 // Now add all bases.
1744 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001745 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001746}
1747
Douglas Gregor88d292c2010-05-13 16:44:06 +00001748/// \brief Determine whether the given base path includes a virtual
1749/// base class.
John McCallcf142162010-08-07 06:22:56 +00001750bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1751 for (CXXCastPath::const_iterator B = BasePath.begin(),
1752 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001753 B != BEnd; ++B)
1754 if ((*B)->isVirtual())
1755 return true;
1756
1757 return false;
1758}
1759
Douglas Gregor36d1b142009-10-06 17:59:45 +00001760/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1761/// conversion (where Derived and Base are class types) is
1762/// well-formed, meaning that the conversion is unambiguous (and
1763/// that all of the base classes are accessible). Returns true
1764/// and emits a diagnostic if the code is ill-formed, returns false
1765/// otherwise. Loc is the location where this routine should point to
1766/// if there is an error, and Range is the source range to highlight
1767/// if there is an error.
1768bool
1769Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001770 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771 unsigned AmbigiousBaseConvID,
1772 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001773 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001774 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001775 // First, determine whether the path from Derived to Base is
1776 // ambiguous. This is slightly more expensive than checking whether
1777 // the Derived to Base conversion exists, because here we need to
1778 // explore multiple paths to determine if there is an ambiguity.
1779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1780 /*DetectVirtual=*/false);
1781 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1782 assert(DerivationOkay &&
1783 "Can only be used with a derived-to-base conversion");
1784 (void)DerivationOkay;
1785
1786 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001787 if (InaccessibleBaseID) {
1788 // Check that the base class can be accessed.
1789 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1790 InaccessibleBaseID)) {
1791 case AR_inaccessible:
1792 return true;
1793 case AR_accessible:
1794 case AR_dependent:
1795 case AR_delayed:
1796 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001797 }
John McCall5b0829a2010-02-10 09:31:12 +00001798 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001799
1800 // Build a base path if necessary.
1801 if (BasePath)
1802 BuildBasePathArray(Paths, *BasePath);
1803 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001804 }
1805
David Majnemer626032f2013-06-22 06:43:58 +00001806 if (AmbigiousBaseConvID) {
1807 // We know that the derived-to-base conversion is ambiguous, and
1808 // we're going to produce a diagnostic. Perform the derived-to-base
1809 // search just one more time to compute all of the possible paths so
1810 // that we can print them out. This is more expensive than any of
1811 // the previous derived-to-base checks we've done, but at this point
1812 // performance isn't as much of an issue.
1813 Paths.clear();
1814 Paths.setRecordingPaths(true);
1815 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1816 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1817 (void)StillOkay;
1818
1819 // Build up a textual representation of the ambiguous paths, e.g.,
1820 // D -> B -> A, that will be used to illustrate the ambiguous
1821 // conversions in the diagnostic. We only print one of the paths
1822 // to each base class subobject.
1823 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1824
1825 Diag(Loc, AmbigiousBaseConvID)
1826 << Derived << Base << PathDisplayStr << Range << Name;
1827 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001828 return true;
1829}
1830
1831bool
1832Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001833 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001834 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001835 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001836 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001837 IgnoreAccess ? 0
1838 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001839 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001840 Loc, Range, DeclarationName(),
1841 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001842}
1843
1844
1845/// @brief Builds a string representing ambiguous paths from a
1846/// specific derived class to different subobjects of the same base
1847/// class.
1848///
1849/// This function builds a string that can be used in error messages
1850/// to show the different paths that one can take through the
1851/// inheritance hierarchy to go from the derived class to different
1852/// subobjects of a base class. The result looks something like this:
1853/// @code
1854/// struct D -> struct B -> struct A
1855/// struct D -> struct C -> struct A
1856/// @endcode
1857std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1858 std::string PathDisplayStr;
1859 std::set<unsigned> DisplayedPaths;
1860 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1861 Path != Paths.end(); ++Path) {
1862 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1863 // We haven't displayed a path to this particular base
1864 // class subobject yet.
1865 PathDisplayStr += "\n ";
1866 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1867 for (CXXBasePath::const_iterator Element = Path->begin();
1868 Element != Path->end(); ++Element)
1869 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1870 }
1871 }
1872
1873 return PathDisplayStr;
1874}
1875
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001876//===----------------------------------------------------------------------===//
1877// C++ class member Handling
1878//===----------------------------------------------------------------------===//
1879
Abramo Bagnarad7340582010-06-05 05:09:32 +00001880/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001881bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1882 SourceLocation ASLoc,
1883 SourceLocation ColonLoc,
1884 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001885 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001886 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001887 ASLoc, ColonLoc);
1888 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001889 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001890}
1891
Richard Smith18f07db2012-08-06 03:25:17 +00001892/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001893void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001894 if (D->isInvalidDecl())
1895 return;
1896
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001897 // We only care about "override" and "final" declarations.
1898 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1899 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001900
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001901 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001902
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001903 // We can't check dependent instance methods.
1904 if (MD && MD->isInstance() &&
1905 (MD->getParent()->hasAnyDependentBases() ||
1906 MD->getType()->isDependentType()))
1907 return;
1908
1909 if (MD && !MD->isVirtual()) {
1910 // If we have a non-virtual method, check if if hides a virtual method.
1911 // (In that case, it's most likely the method has the wrong type.)
1912 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1913 FindHiddenVirtualMethods(MD, OverloadedMethods);
1914
1915 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001916 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1917 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001918 diag::override_keyword_hides_virtual_member_function)
1919 << "override" << (OverloadedMethods.size() > 1);
1920 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001921 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001922 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001923 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1924 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001925 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001926 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1927 MD->setInvalidDecl();
1928 return;
1929 }
1930 // Fall through into the general case diagnostic.
1931 // FIXME: We might want to attempt typo correction here.
1932 }
1933
1934 if (!MD || !MD->isVirtual()) {
1935 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1936 Diag(OA->getLocation(),
1937 diag::override_keyword_only_allowed_on_virtual_member_functions)
1938 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1939 D->dropAttr<OverrideAttr>();
1940 }
1941 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1942 Diag(FA->getLocation(),
1943 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001944 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1945 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001946 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001947 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001948 return;
1949 }
Richard Smith18f07db2012-08-06 03:25:17 +00001950
Richard Smith18f07db2012-08-06 03:25:17 +00001951 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001952 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001953 // does not override a member function of a base class, the program is
1954 // ill-formed.
1955 bool HasOverriddenMethods =
1956 MD->begin_overridden_methods() != MD->end_overridden_methods();
1957 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1958 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1959 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001960}
1961
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001962void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1963 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1964 return;
1965 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1966 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1967 isa<CXXDestructorDecl>(MD))
1968 return;
1969
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001970 SourceLocation Loc = MD->getLocation();
1971 SourceLocation SpellingLoc = Loc;
1972 if (getSourceManager().isMacroArgExpansion(Loc))
1973 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1974 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1975 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001976 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001977
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001978 if (MD->size_overridden_methods() > 0) {
1979 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1980 << MD->getDeclName();
1981 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1982 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1983 }
1984}
1985
Richard Smith18f07db2012-08-06 03:25:17 +00001986/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001987/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001988/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001989bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1990 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001991 FinalAttr *FA = Old->getAttr<FinalAttr>();
1992 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001993 return false;
1994
1995 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001996 << New->getDeclName()
1997 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001998 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1999 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002000}
2001
Daniel Jasper0baec5492012-06-06 08:32:04 +00002002static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002003 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2004 // FIXME: Destruction of ObjC lifetime types has side-effects.
2005 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2006 return !RD->isCompleteDefinition() ||
2007 !RD->hasTrivialDefaultConstructor() ||
2008 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002009 return false;
2010}
2011
John McCall5e77d762013-04-16 07:28:30 +00002012static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002013 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002014 if (it->isDeclspecPropertyAttribute())
2015 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002016 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002017}
2018
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002019/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2020/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002021/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002022/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2023/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002024NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002025Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002026 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002027 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002028 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002029 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002030 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2031 DeclarationName Name = NameInfo.getName();
2032 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002033
2034 // For anonymous bitfields, the location should point to the type.
2035 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002036 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002037
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002038 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002039
John McCallb1cd7da2010-06-04 08:34:12 +00002040 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002041 assert(!DS.isFriendSpecified());
2042
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002043 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002044
John McCalldb632ac2012-09-25 07:32:39 +00002045 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2046 // The Microsoft extension __interface only permits public member functions
2047 // and prohibits constructors, destructors, operators, non-public member
2048 // functions, static methods and data members.
2049 unsigned InvalidDecl;
2050 bool ShowDeclName = true;
2051 if (!isFunc)
2052 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2053 else if (AS != AS_public)
2054 InvalidDecl = 2;
2055 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2056 InvalidDecl = 3;
2057 else switch (Name.getNameKind()) {
2058 case DeclarationName::CXXConstructorName:
2059 InvalidDecl = 4;
2060 ShowDeclName = false;
2061 break;
2062
2063 case DeclarationName::CXXDestructorName:
2064 InvalidDecl = 5;
2065 ShowDeclName = false;
2066 break;
2067
2068 case DeclarationName::CXXOperatorName:
2069 case DeclarationName::CXXConversionFunctionName:
2070 InvalidDecl = 6;
2071 break;
2072
2073 default:
2074 InvalidDecl = 0;
2075 break;
2076 }
2077
2078 if (InvalidDecl) {
2079 if (ShowDeclName)
2080 Diag(Loc, diag::err_invalid_member_in_interface)
2081 << (InvalidDecl-1) << Name;
2082 else
2083 Diag(Loc, diag::err_invalid_member_in_interface)
2084 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002085 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002086 }
2087 }
2088
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002089 // C++ 9.2p6: A member shall not be declared to have automatic storage
2090 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002091 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2092 // data members and cannot be applied to names declared const or static,
2093 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002094 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002095 case DeclSpec::SCS_unspecified:
2096 case DeclSpec::SCS_typedef:
2097 case DeclSpec::SCS_static:
2098 break;
2099 case DeclSpec::SCS_mutable:
2100 if (isFunc) {
2101 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Richard Smithb4a9e862013-04-12 22:46:28 +00002103 // FIXME: It would be nicer if the keyword was ignored only for this
2104 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002105 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002106 }
2107 break;
2108 default:
2109 Diag(DS.getStorageClassSpecLoc(),
2110 diag::err_storageclass_invalid_for_member);
2111 D.getMutableDeclSpec().ClearStorageClassSpecs();
2112 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002113 }
2114
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002115 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2116 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002117 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002118
David Blaikie35506f82013-01-30 01:22:18 +00002119 if (DS.isConstexprSpecified() && isInstField) {
2120 SemaDiagnosticBuilder B =
2121 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2122 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2123 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002124 B << 0 << 0;
2125 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2126 B << FixItHint::CreateRemoval(ConstexprLoc);
2127 else {
2128 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2129 D.getMutableDeclSpec().ClearConstexprSpec();
2130 const char *PrevSpec;
2131 unsigned DiagID;
2132 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2133 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2134 (void)Failed;
2135 assert(!Failed && "Making a constexpr member const shouldn't fail");
2136 }
David Blaikie35506f82013-01-30 01:22:18 +00002137 } else {
2138 B << 1;
2139 const char *PrevSpec;
2140 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002141 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002142 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2143 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002144 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002145 "This is the only DeclSpec that should fail to be applied");
2146 B << 1;
2147 } else {
2148 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2149 isInstField = false;
2150 }
2151 }
2152 }
2153
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002154 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002155 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002156 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002157
2158 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002159 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002160 Diag(Loc, diag::err_bad_variable_name)
2161 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002163 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002164
Benjamin Kramer365082d2012-05-19 16:34:46 +00002165 IdentifierInfo *II = Name.getAsIdentifierInfo();
2166
Douglas Gregor7c26c042011-09-21 14:40:46 +00002167 // Member field could not be with "template" keyword.
2168 // So TemplateParameterLists should be empty in this case.
2169 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002170 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002171 if (TemplateParams->size()) {
2172 // There is no such thing as a member field template.
2173 Diag(D.getIdentifierLoc(), diag::err_template_member)
2174 << II
2175 << SourceRange(TemplateParams->getTemplateLoc(),
2176 TemplateParams->getRAngleLoc());
2177 } else {
2178 // There is an extraneous 'template<>' for this member.
2179 Diag(TemplateParams->getTemplateLoc(),
2180 diag::err_template_member_noparams)
2181 << II
2182 << SourceRange(TemplateParams->getTemplateLoc(),
2183 TemplateParams->getRAngleLoc());
2184 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002185 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002186 }
2187
Douglas Gregora007d362010-10-13 22:19:53 +00002188 if (SS.isSet() && !SS.isInvalid()) {
2189 // The user provided a superfluous scope specifier inside a class
2190 // definition:
2191 //
2192 // class X {
2193 // int X::member;
2194 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002195 if (DeclContext *DC = computeDeclContext(SS, false))
2196 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002197 else
2198 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2199 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002200
Douglas Gregora007d362010-10-13 22:19:53 +00002201 SS.clear();
2202 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002203
John McCall5e77d762013-04-16 07:28:30 +00002204 AttributeList *MSPropertyAttr =
2205 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002206 if (MSPropertyAttr) {
2207 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2208 BitWidth, InitStyle, AS, MSPropertyAttr);
2209 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002210 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002211 isInstField = false;
2212 } else {
2213 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2214 BitWidth, InitStyle, AS);
2215 assert(Member && "HandleField never returns null");
2216 }
2217 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002218 assert(InitStyle == ICIS_NoInit ||
2219 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002220
2221 Member = HandleDeclarator(S, D, TemplateParameterLists);
2222 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002223 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002224
2225 // Non-instance-fields can't have a bitfield.
2226 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002227 if (Member->isInvalidDecl()) {
2228 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002229 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002230 // C++ 9.6p3: A bit-field shall not be a static member.
2231 // "static member 'A' cannot be a bit-field"
2232 Diag(Loc, diag::err_static_not_bitfield)
2233 << Name << BitWidth->getSourceRange();
2234 } else if (isa<TypedefDecl>(Member)) {
2235 // "typedef member 'x' cannot be a bit-field"
2236 Diag(Loc, diag::err_typedef_not_bitfield)
2237 << Name << BitWidth->getSourceRange();
2238 } else {
2239 // A function typedef ("typedef int f(); f a;").
2240 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2241 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002242 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002243 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002244 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
Craig Topperc3ec1492014-05-26 06:22:03 +00002246 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002247 Member->setInvalidDecl();
2248 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002249
2250 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002251
Larisse Voufo39a1e502013-08-06 01:03:05 +00002252 // If we have declared a member function template or static data member
2253 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002254 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2255 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002256 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2257 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002258 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002259
Richard Smith18f07db2012-08-06 03:25:17 +00002260 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002261 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002262 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002263 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2264 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002265
Douglas Gregorf2f08062011-03-08 17:10:18 +00002266 if (VS.getLastLocation().isValid()) {
2267 // Update the end location of a method that has a virt-specifiers.
2268 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2269 MD->setRangeEnd(VS.getLastLocation());
2270 }
Richard Smith18f07db2012-08-06 03:25:17 +00002271
Anders Carlssonc87f8612011-01-20 06:29:02 +00002272 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002273
Douglas Gregor92751d42008-11-17 22:58:34 +00002274 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002275
Daniel Jasper0baec5492012-06-06 08:32:04 +00002276 if (isInstField) {
2277 FieldDecl *FD = cast<FieldDecl>(Member);
2278 FieldCollector->Add(FD);
2279
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002280 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002281 // Remember all explicit private FieldDecls that have a name, no side
2282 // effects and are not part of a dependent type declaration.
2283 if (!FD->isImplicit() && FD->getDeclName() &&
2284 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002285 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002286 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002287 !InitializationHasSideEffects(*FD))
2288 UnusedPrivateFields.insert(FD);
2289 }
2290 }
2291
John McCall48871652010-08-21 09:40:31 +00002292 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002293}
2294
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002295namespace {
2296 class UninitializedFieldVisitor
2297 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2298 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002299 // List of Decls to generate a warning on. Also remove Decls that become
2300 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002301 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002302 // List of base classes of the record. Classes are removed after their
2303 // initializers.
2304 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002305 // Vector of decls to be removed from the Decl set prior to visiting the
2306 // nodes. These Decls may have been initialized in the prior initializer.
2307 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002308 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002309 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002310 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002311 // InitList is true, special case initialization of FieldDecls matching
2312 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002313 bool InitList;
2314 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002315 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2316
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002317 public:
2318 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002319 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002320 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2321 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2322 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2323 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002324
Richard Trieufa1d0a72014-10-17 20:56:10 +00002325 // Returns true if the use of ME is not an uninitialized use.
2326 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2327 bool CheckReferenceOnly) {
2328 llvm::SmallVector<FieldDecl*, 4> Fields;
2329 bool ReferenceField = false;
2330 while (ME) {
2331 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2332 if (!FD)
2333 return false;
2334 Fields.push_back(FD);
2335 if (FD->getType()->isReferenceType())
2336 ReferenceField = true;
2337 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2338 }
2339
2340 // Binding a reference to an unintialized field is not an
2341 // uninitialized use.
2342 if (CheckReferenceOnly && !ReferenceField)
2343 return true;
2344
2345 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2346 // Discard the first field since it is the field decl that is being
2347 // initialized.
2348 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2349 UsedFieldIndex.push_back((*I)->getFieldIndex());
2350 }
2351
2352 for (auto UsedIter = UsedFieldIndex.begin(),
2353 UsedEnd = UsedFieldIndex.end(),
2354 OrigIter = InitFieldIndex.begin(),
2355 OrigEnd = InitFieldIndex.end();
2356 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2357 if (*UsedIter < *OrigIter)
2358 return true;
2359 if (*UsedIter > *OrigIter)
2360 break;
2361 }
2362
2363 return false;
2364 }
2365
Richard Trieu2d779b92014-10-01 03:44:58 +00002366 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2367 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002368 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2369 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002370
Richard Trieu1bc22c12013-09-13 03:20:53 +00002371 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2372 // or union.
2373 MemberExpr *FieldME = ME;
2374
Richard Trieu2d779b92014-10-01 03:44:58 +00002375 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2376
Richard Trieu1bc22c12013-09-13 03:20:53 +00002377 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002378 while (MemberExpr *SubME =
2379 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002380
Richard Trieufa1d0a72014-10-17 20:56:10 +00002381 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002382 return;
2383
Richard Trieufa1d0a72014-10-17 20:56:10 +00002384 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002385 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002386 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002387
Richard Trieu2d779b92014-10-01 03:44:58 +00002388 if (!FieldME->getType().isPODType(S.Context))
2389 AllPODFields = false;
2390
Richard Trieu3630c392014-11-21 03:10:30 +00002391 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002392 }
2393
Richard Trieu3630c392014-11-21 03:10:30 +00002394 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002395 return;
2396
Richard Trieu2d779b92014-10-01 03:44:58 +00002397 if (AddressOf && AllPODFields)
2398 return;
2399
Richard Trieu406e65c2013-09-20 03:03:06 +00002400 ValueDecl* FoundVD = FieldME->getMemberDecl();
2401
Richard Trieu3630c392014-11-21 03:10:30 +00002402 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2403 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2404 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2405 }
2406
2407 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2408 QualType T = BaseCast->getType();
2409 if (T->isPointerType() &&
2410 BaseClasses.count(T->getPointeeType())) {
2411 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2412 << T->getPointeeType() << FoundVD;
2413 }
2414 }
2415 }
2416
Richard Trieuef64e942013-10-25 00:56:00 +00002417 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002418 return;
2419
Richard Trieuef64e942013-10-25 00:56:00 +00002420 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002421
Richard Trieufa1d0a72014-10-17 20:56:10 +00002422 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2423 // Special checking for initializer lists.
2424 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2425 return;
2426 }
2427 } else {
2428 // Prevent double warnings on use of unbounded references.
2429 if (CheckReferenceOnly && !IsReference)
2430 return;
2431 }
Richard Trieuef64e942013-10-25 00:56:00 +00002432
2433 unsigned diag = IsReference
2434 ? diag::warn_reference_field_is_uninit
2435 : diag::warn_field_is_uninit;
2436 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2437 if (Constructor)
2438 S.Diag(Constructor->getLocation(),
2439 diag::note_uninit_in_this_constructor)
2440 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2441
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002442 }
2443
Richard Trieu2d779b92014-10-01 03:44:58 +00002444 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002445 E = E->IgnoreParens();
2446
2447 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002448 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2449 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002450 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002451 }
2452
2453 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002454 Visit(CO->getCond());
2455 HandleValue(CO->getTrueExpr(), AddressOf);
2456 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002457 return;
2458 }
2459
2460 if (BinaryConditionalOperator *BCO =
2461 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002462 Visit(BCO->getCond());
2463 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002464 return;
2465 }
2466
Richard Trieuabf6ec42014-08-27 22:15:10 +00002467 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002468 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002469 return;
2470 }
2471
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002472 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2473 switch (BO->getOpcode()) {
2474 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002475 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002476 case(BO_PtrMemD):
2477 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002478 HandleValue(BO->getLHS(), AddressOf);
2479 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002480 return;
2481 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002482 Visit(BO->getLHS());
2483 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002484 return;
2485 }
2486 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002487
2488 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002489 }
2490
Richard Trieufa1d0a72014-10-17 20:56:10 +00002491 void CheckInitListExpr(InitListExpr *ILE) {
2492 InitFieldIndex.push_back(0);
2493 for (auto Child : ILE->children()) {
2494 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2495 CheckInitListExpr(SubList);
2496 } else {
2497 Visit(Child);
2498 }
2499 ++InitFieldIndex.back();
2500 }
2501 InitFieldIndex.pop_back();
2502 }
2503
Richard Trieu8d08a272014-08-28 03:23:47 +00002504 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002505 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002506 // Remove Decls that may have been initialized in the previous
2507 // initializer.
2508 for (ValueDecl* VD : DeclsToRemove)
2509 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002510 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002511
Richard Trieu8d08a272014-08-28 03:23:47 +00002512 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002513 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2514
2515 if (ILE && Field) {
2516 InitList = true;
2517 InitListFieldDecl = Field;
2518 InitFieldIndex.clear();
2519 CheckInitListExpr(ILE);
2520 } else {
2521 InitList = false;
2522 Visit(E);
2523 }
2524
Richard Trieu8d08a272014-08-28 03:23:47 +00002525 if (Field)
2526 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002527 if (BaseClass)
2528 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002529 }
2530
Richard Trieu1bc22c12013-09-13 03:20:53 +00002531 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002532 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002533 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002534 }
2535
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002536 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002537 if (E->getCastKind() == CK_LValueToRValue) {
2538 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2539 return;
2540 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002541
2542 Inherited::VisitImplicitCastExpr(E);
2543 }
2544
Richard Trieu1bc22c12013-09-13 03:20:53 +00002545 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002546 if (E->getConstructor()->isCopyConstructor()) {
2547 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002548 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2549 if (ILE->getNumInits() == 1)
2550 ArgExpr = ILE->getInit(0);
2551 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2552 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002553 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002554 HandleValue(ArgExpr, false /*AddressOf*/);
2555 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002556 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002557 Inherited::VisitCXXConstructExpr(E);
2558 }
2559
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002560 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2561 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002562 if (isa<MemberExpr>(Callee)) {
2563 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002564 for (auto Arg : E->arguments())
2565 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002566 return;
2567 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002568
2569 Inherited::VisitCXXMemberCallExpr(E);
2570 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002571
Richard Trieu11fd0792014-08-26 04:30:55 +00002572 void VisitCallExpr(CallExpr *E) {
2573 // Treat std::move as a use.
2574 if (E->getNumArgs() == 1) {
2575 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002576 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2577 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002578 HandleValue(E->getArg(0), false /*AddressOf*/);
2579 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002580 }
2581 }
2582 }
2583
2584 Inherited::VisitCallExpr(E);
2585 }
2586
Richard Trieud4a01362014-10-31 21:10:22 +00002587 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2588 Expr *Callee = E->getCallee();
2589
2590 if (isa<UnresolvedLookupExpr>(Callee))
2591 return Inherited::VisitCXXOperatorCallExpr(E);
2592
2593 Visit(Callee);
2594 for (auto Arg : E->arguments())
2595 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2596 }
2597
Richard Trieu406e65c2013-09-20 03:03:06 +00002598 void VisitBinaryOperator(BinaryOperator *E) {
2599 // If a field assignment is detected, remove the field from the
2600 // uninitiailized field set.
2601 if (E->getOpcode() == BO_Assign)
2602 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2603 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002604 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002605 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002606
Richard Trieu52b8b602014-09-25 01:15:40 +00002607 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002608 HandleValue(E->getLHS(), false /*AddressOf*/);
2609 Visit(E->getRHS());
2610 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002611 }
2612
Richard Trieu406e65c2013-09-20 03:03:06 +00002613 Inherited::VisitBinaryOperator(E);
2614 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002615
2616 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002617 if (E->isIncrementDecrementOp()) {
2618 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2619 return;
2620 }
2621 if (E->getOpcode() == UO_AddrOf) {
2622 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2623 HandleValue(ME->getBase(), true /*AddressOf*/);
2624 return;
2625 }
2626 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002627
2628 Inherited::VisitUnaryOperator(E);
2629 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002630 };
Richard Trieuef64e942013-10-25 00:56:00 +00002631
2632 // Diagnose value-uses of fields to initialize themselves, e.g.
2633 // foo(foo)
2634 // where foo is not also a parameter to the constructor.
2635 // Also diagnose across field uninitialized use such as
2636 // x(y), y(x)
2637 // TODO: implement -Wuninitialized and fold this into that framework.
2638 static void DiagnoseUninitializedFields(
2639 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2640
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002641 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2642 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002643 return;
2644 }
2645
2646 if (Constructor->isInvalidDecl())
2647 return;
2648
2649 const CXXRecordDecl *RD = Constructor->getParent();
2650
Richard Trieu353a4b42014-10-22 05:21:59 +00002651 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002652 return;
2653
Richard Trieuef64e942013-10-25 00:56:00 +00002654 // Holds fields that are uninitialized.
2655 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2656
2657 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002658 for (auto *I : RD->decls()) {
2659 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002660 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002661 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002662 UninitializedFields.insert(IFD->getAnonField());
2663 }
2664 }
2665
Richard Trieu3630c392014-11-21 03:10:30 +00002666 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2667 for (auto I : RD->bases())
2668 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2669
2670 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002671 return;
2672
2673 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002674 UninitializedFields,
2675 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002676
Aaron Ballman0ad78302014-03-13 17:34:31 +00002677 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002678 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002679 break;
2680
Aaron Ballman0ad78302014-03-13 17:34:31 +00002681 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002682 if (!InitExpr)
2683 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002684
Richard Trieu8d08a272014-08-28 03:23:47 +00002685 if (CXXDefaultInitExpr *Default =
2686 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2687 InitExpr = Default->getExpr();
2688 if (!InitExpr)
2689 continue;
2690 // In class initializers will point to the constructor.
2691 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002692 FieldInit->getAnyMember(),
2693 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002694 } else {
2695 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002696 FieldInit->getAnyMember(),
2697 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002698 }
Richard Trieuef64e942013-10-25 00:56:00 +00002699 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002700 }
2701} // namespace
2702
Richard Smith74108172014-01-17 03:11:34 +00002703/// \brief Enter a new C++ default initializer scope. After calling this, the
2704/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2705/// parsing or instantiating the initializer failed.
2706void Sema::ActOnStartCXXInClassMemberInitializer() {
2707 // Create a synthetic function scope to represent the call to the constructor
2708 // that notionally surrounds a use of this initializer.
2709 PushFunctionScope();
2710}
2711
2712/// \brief This is invoked after parsing an in-class initializer for a
2713/// non-static C++ class member, and after instantiating an in-class initializer
2714/// in a class template. Such actions are deferred until the class is complete.
2715void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2716 SourceLocation InitLoc,
2717 Expr *InitExpr) {
2718 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002719 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002720
David Majnemer87ff66c2014-12-13 11:34:16 +00002721 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2722 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002723 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002724
2725 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002726 D->setInvalidDecl();
2727 if (FD)
2728 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002729 return;
2730 }
2731
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002732 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2733 FD->setInvalidDecl();
2734 FD->removeInClassInitializer();
2735 return;
2736 }
2737
Richard Smith938f40b2011-06-11 17:19:42 +00002738 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002739 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002740 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002741 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002742 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002743 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002744 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2745 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002746 if (Init.isInvalid()) {
2747 FD->setInvalidDecl();
2748 return;
2749 }
Richard Smith938f40b2011-06-11 17:19:42 +00002750 }
2751
Richard Smith945f8d32013-01-14 22:39:08 +00002752 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002753 // The initialization of each base and member constitutes a
2754 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002755 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002756 if (Init.isInvalid()) {
2757 FD->setInvalidDecl();
2758 return;
2759 }
2760
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002761 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002762
2763 FD->setInClassInitializer(InitExpr);
2764}
2765
Douglas Gregor15e77a22009-12-31 09:10:24 +00002766/// \brief Find the direct and/or virtual base specifiers that
2767/// correspond to the given base type, for use in base initialization
2768/// within a constructor.
2769static bool FindBaseInitializer(Sema &SemaRef,
2770 CXXRecordDecl *ClassDecl,
2771 QualType BaseType,
2772 const CXXBaseSpecifier *&DirectBaseSpec,
2773 const CXXBaseSpecifier *&VirtualBaseSpec) {
2774 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002775 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002776 for (const auto &Base : ClassDecl->bases()) {
2777 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002778 // We found a direct base of this type. That's what we're
2779 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002780 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002781 break;
2782 }
2783 }
2784
2785 // Check for a virtual base class.
2786 // FIXME: We might be able to short-circuit this if we know in advance that
2787 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002788 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002789 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2790 // We haven't found a base yet; search the class hierarchy for a
2791 // virtual base class.
2792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2793 /*DetectVirtual=*/false);
2794 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2795 BaseType, Paths)) {
2796 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2797 Path != Paths.end(); ++Path) {
2798 if (Path->back().Base->isVirtual()) {
2799 VirtualBaseSpec = Path->back().Base;
2800 break;
2801 }
2802 }
2803 }
2804 }
2805
2806 return DirectBaseSpec || VirtualBaseSpec;
2807}
2808
Sebastian Redla74948d2011-09-24 17:48:25 +00002809/// \brief Handle a C++ member initializer using braced-init-list syntax.
2810MemInitResult
2811Sema::ActOnMemInitializer(Decl *ConstructorD,
2812 Scope *S,
2813 CXXScopeSpec &SS,
2814 IdentifierInfo *MemberOrBase,
2815 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002816 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002817 SourceLocation IdLoc,
2818 Expr *InitList,
2819 SourceLocation EllipsisLoc) {
2820 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002821 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002822 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002823}
2824
2825/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002826MemInitResult
John McCall48871652010-08-21 09:40:31 +00002827Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002828 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002829 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002830 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002831 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002832 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002833 SourceLocation IdLoc,
2834 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002835 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002836 SourceLocation RParenLoc,
2837 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002838 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002839 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002840 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002841 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002842}
2843
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002844namespace {
2845
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002846// Callback to only accept typo corrections that can be a valid C++ member
2847// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002848class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002849public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002850 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2851 : ClassDecl(ClassDecl) {}
2852
Craig Toppera798a9d2014-03-02 09:32:10 +00002853 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002854 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2855 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2856 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002857 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002858 }
2859 return false;
2860 }
2861
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002862private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002863 CXXRecordDecl *ClassDecl;
2864};
2865
2866}
2867
Sebastian Redla74948d2011-09-24 17:48:25 +00002868/// \brief Handle a C++ member initializer.
2869MemInitResult
2870Sema::BuildMemInitializer(Decl *ConstructorD,
2871 Scope *S,
2872 CXXScopeSpec &SS,
2873 IdentifierInfo *MemberOrBase,
2874 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002875 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002876 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002877 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002878 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002879 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2880 if (!Res.isUsable())
2881 return true;
2882 Init = Res.get();
2883
Douglas Gregor71a57182009-06-22 23:20:33 +00002884 if (!ConstructorD)
2885 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002886
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002887 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002888
2889 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002890 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002891 if (!Constructor) {
2892 // The user wrote a constructor initializer on a function that is
2893 // not a C++ constructor. Ignore the error for now, because we may
2894 // have more member initializers coming; we'll diagnose it just
2895 // once in ActOnMemInitializers.
2896 return true;
2897 }
2898
2899 CXXRecordDecl *ClassDecl = Constructor->getParent();
2900
2901 // C++ [class.base.init]p2:
2902 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002903 // constructor's class and, if not found in that scope, are looked
2904 // up in the scope containing the constructor's definition.
2905 // [Note: if the constructor's class contains a member with the
2906 // same name as a direct or virtual base class of the class, a
2907 // mem-initializer-id naming the member or base class and composed
2908 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002909 // mem-initializer-id for the hidden base class may be specified
2910 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002911 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002912 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002913 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002914 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002915 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002916 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2917 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002918 if (EllipsisLoc.isValid())
2919 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002920 << MemberOrBase
2921 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002922
Sebastian Redla9351792012-02-11 23:51:47 +00002923 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002924 }
Francois Pichetd583da02010-12-04 09:14:42 +00002925 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002926 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002927 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002928 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002929 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002930
2931 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002932 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002933 } else if (DS.getTypeSpecType() == TST_decltype) {
2934 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002935 } else {
2936 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2937 LookupParsedName(R, S, &SS);
2938
2939 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2940 if (!TyD) {
2941 if (R.isAmbiguous()) return true;
2942
John McCallda6841b2010-04-09 19:01:14 +00002943 // We don't want access-control diagnostics here.
2944 R.suppressDiagnostics();
2945
Douglas Gregora3b624a2010-01-19 06:46:48 +00002946 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2947 bool NotUnknownSpecialization = false;
2948 DeclContext *DC = computeDeclContext(SS, false);
2949 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2950 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2951
2952 if (!NotUnknownSpecialization) {
2953 // When the scope specifier can refer to a member of an unknown
2954 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002955 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2956 SS.getWithLocInContext(Context),
2957 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002958 if (BaseType.isNull())
2959 return true;
2960
Douglas Gregora3b624a2010-01-19 06:46:48 +00002961 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002962 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002963 }
2964 }
2965
Douglas Gregor15e77a22009-12-31 09:10:24 +00002966 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002967 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002968 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002969 (Corr = CorrectTypo(
2970 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2971 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2972 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002973 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002974 // We have found a non-static data member with a similar
2975 // name to what was typed; complain and initialize that
2976 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002977 diagnoseTypo(Corr,
2978 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2979 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002980 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002981 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002982 const CXXBaseSpecifier *DirectBaseSpec;
2983 const CXXBaseSpecifier *VirtualBaseSpec;
2984 if (FindBaseInitializer(*this, ClassDecl,
2985 Context.getTypeDeclType(Type),
2986 DirectBaseSpec, VirtualBaseSpec)) {
2987 // We have found a direct or virtual base class with a
2988 // similar name to what was typed; complain and initialize
2989 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002990 diagnoseTypo(Corr,
2991 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2992 << MemberOrBase << false,
2993 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002994
Richard Smithf9b15102013-08-17 00:46:16 +00002995 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2996 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002997 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002998 diag::note_base_class_specified_here)
2999 << BaseSpec->getType()
3000 << BaseSpec->getSourceRange();
3001
Douglas Gregor15e77a22009-12-31 09:10:24 +00003002 TyD = Type;
3003 }
3004 }
3005 }
3006
Douglas Gregora3b624a2010-01-19 06:46:48 +00003007 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003008 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003009 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003010 return true;
3011 }
John McCallb5a0d312009-12-21 10:41:20 +00003012 }
3013
Douglas Gregora3b624a2010-01-19 06:46:48 +00003014 if (BaseType.isNull()) {
3015 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003016 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00003017 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00003018 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00003019 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3020 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00003021 }
3022 }
Mike Stump11289f42009-09-09 15:08:12 +00003023
John McCallbcd03502009-12-07 02:54:59 +00003024 if (!TInfo)
3025 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003026
Sebastian Redla9351792012-02-11 23:51:47 +00003027 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003028}
3029
Chandler Carruth599deef2011-09-03 01:14:15 +00003030/// Checks a member initializer expression for cases where reference (or
3031/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003032static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3033 Expr *Init,
3034 SourceLocation IdLoc) {
3035 QualType MemberTy = Member->getType();
3036
3037 // We only handle pointers and references currently.
3038 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3039 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3040 return;
3041
3042 const bool IsPointer = MemberTy->isPointerType();
3043 if (IsPointer) {
3044 if (const UnaryOperator *Op
3045 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3046 // The only case we're worried about with pointers requires taking the
3047 // address.
3048 if (Op->getOpcode() != UO_AddrOf)
3049 return;
3050
3051 Init = Op->getSubExpr();
3052 } else {
3053 // We only handle address-of expression initializers for pointers.
3054 return;
3055 }
3056 }
3057
Richard Smithe3b28bc2013-06-12 21:51:50 +00003058 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003059 // We only warn when referring to a non-reference parameter declaration.
3060 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3061 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003062 return;
3063
3064 S.Diag(Init->getExprLoc(),
3065 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3066 : diag::warn_bind_ref_member_to_parameter)
3067 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003068 } else {
3069 // Other initializers are fine.
3070 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003071 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003072
3073 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3074 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003075}
3076
John McCallfaf5fb42010-08-26 23:41:50 +00003077MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003078Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003079 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003080 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3081 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3082 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003083 "Member must be a FieldDecl or IndirectFieldDecl");
3084
Sebastian Redla9351792012-02-11 23:51:47 +00003085 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003086 return true;
3087
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003088 if (Member->isInvalidDecl())
3089 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003090
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003091 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003092 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003093 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003094 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003095 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003096 } else {
3097 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003098 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003099 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003100
Sebastian Redla9351792012-02-11 23:51:47 +00003101 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003102
Sebastian Redla9351792012-02-11 23:51:47 +00003103 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003104 // Can't check initialization for a member of dependent type or when
3105 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003106 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003107 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003108 bool InitList = false;
3109 if (isa<InitListExpr>(Init)) {
3110 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003111 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003112 }
3113
Chandler Carruthd44c3102010-12-06 09:23:57 +00003114 // Initialize the member.
3115 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003116 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3117 : InitializedEntity::InitializeMember(IndirectMember,
3118 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003119 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003120 InitList ? InitializationKind::CreateDirectList(IdLoc)
3121 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3122 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003123
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003124 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003125 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3126 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003127 if (MemberInit.isInvalid())
3128 return true;
3129
Richard Smith736a9472013-06-12 20:42:33 +00003130 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3131
Richard Smith945f8d32013-01-14 22:39:08 +00003132 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003133 // The initialization of each base and member constitutes a
3134 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003135 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003136 if (MemberInit.isInvalid())
3137 return true;
3138
Richard Smithd59b8322012-12-19 01:39:02 +00003139 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003140 }
3141
Chandler Carruthd44c3102010-12-06 09:23:57 +00003142 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003143 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3144 InitRange.getBegin(), Init,
3145 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003146 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003147 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3148 InitRange.getBegin(), Init,
3149 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003150 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003151}
3152
John McCallfaf5fb42010-08-26 23:41:50 +00003153MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003154Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003155 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003156 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003157 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003158 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003159 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003160 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003161
Sebastian Redl0501c632012-02-12 16:37:36 +00003162 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003163 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003164 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3165 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003166 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003167 }
3168
Sebastian Redla9351792012-02-11 23:51:47 +00003169 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003170 // Initialize the object.
3171 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3172 QualType(ClassDecl->getTypeForDecl(), 0));
3173 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003174 InitList ? InitializationKind::CreateDirectList(NameLoc)
3175 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3176 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003177 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003178 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003179 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003180 if (DelegationInit.isInvalid())
3181 return true;
3182
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003183 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3184 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003185
Richard Smith945f8d32013-01-14 22:39:08 +00003186 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003187 // The initialization of each base and member constitutes a
3188 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003189 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3190 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003191 if (DelegationInit.isInvalid())
3192 return true;
3193
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003194 // If we are in a dependent context, template instantiation will
3195 // perform this type-checking again. Just save the arguments that we
3196 // received in a ParenListExpr.
3197 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3198 // of the information that we have about the base
3199 // initializer. However, deconstructing the ASTs is a dicey process,
3200 // and this approach is far more likely to get the corner cases right.
3201 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003202 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003203
Sebastian Redla9351792012-02-11 23:51:47 +00003204 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003205 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003206 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003207}
3208
3209MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003210Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003211 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003212 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003213 SourceLocation BaseLoc
3214 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003215
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003216 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3217 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3218 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3219
3220 // C++ [class.base.init]p2:
3221 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003222 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003223 // of that class, the mem-initializer is ill-formed. A
3224 // mem-initializer-list can initialize a base class using any
3225 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003226 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003227
Sebastian Redla9351792012-02-11 23:51:47 +00003228 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003229 if (EllipsisLoc.isValid()) {
3230 // This is a pack expansion.
3231 if (!BaseType->containsUnexpandedParameterPack()) {
3232 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003233 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003234
Douglas Gregor44e7df62011-01-04 00:32:56 +00003235 EllipsisLoc = SourceLocation();
3236 }
3237 } else {
3238 // Check for any unexpanded parameter packs.
3239 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3240 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003241
Sebastian Redla9351792012-02-11 23:51:47 +00003242 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003243 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003244 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003245
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003246 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003247 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3248 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003249 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003250 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3251 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003252 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003253
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003254 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3255 VirtualBaseSpec);
3256
3257 // C++ [base.class.init]p2:
3258 // Unless the mem-initializer-id names a nonstatic data member of the
3259 // constructor's class or a direct or virtual base of that class, the
3260 // mem-initializer is ill-formed.
3261 if (!DirectBaseSpec && !VirtualBaseSpec) {
3262 // If the class has any dependent bases, then it's possible that
3263 // one of those types will resolve to the same type as
3264 // BaseType. Therefore, just treat this as a dependent base
3265 // class initialization. FIXME: Should we try to check the
3266 // initialization anyway? It seems odd.
3267 if (ClassDecl->hasAnyDependentBases())
3268 Dependent = true;
3269 else
3270 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3271 << BaseType << Context.getTypeDeclType(ClassDecl)
3272 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3273 }
3274 }
3275
3276 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003277 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003278
Sebastian Redla74948d2011-09-24 17:48:25 +00003279 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3280 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003281 InitRange.getBegin(), Init,
3282 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003283 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003284
3285 // C++ [base.class.init]p2:
3286 // If a mem-initializer-id is ambiguous because it designates both
3287 // a direct non-virtual base class and an inherited virtual base
3288 // class, the mem-initializer is ill-formed.
3289 if (DirectBaseSpec && VirtualBaseSpec)
3290 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003291 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003292
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003293 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003294 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003295 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003296
3297 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003298 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003299 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003300 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003301 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003302 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003303 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003304
3305 InitializedEntity BaseEntity =
3306 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3307 InitializationKind Kind =
3308 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3309 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3310 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003311 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003312 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003313 if (BaseInit.isInvalid())
3314 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003315
Richard Smith945f8d32013-01-14 22:39:08 +00003316 // C++11 [class.base.init]p7:
3317 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003318 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003319 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003320 if (BaseInit.isInvalid())
3321 return true;
3322
3323 // If we are in a dependent context, template instantiation will
3324 // perform this type-checking again. Just save the arguments that we
3325 // received in a ParenListExpr.
3326 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3327 // of the information that we have about the base
3328 // initializer. However, deconstructing the ASTs is a dicey process,
3329 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003330 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003331 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003332
Alexis Hunt1d792652011-01-08 20:30:50 +00003333 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003334 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003335 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003336 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003337 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003338}
3339
Sebastian Redl22653ba2011-08-30 19:58:05 +00003340// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003341static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3342 if (T.isNull()) T = E->getType();
3343 QualType TargetType = SemaRef.BuildReferenceType(
3344 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003345 SourceLocation ExprLoc = E->getLocStart();
3346 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3347 TargetType, ExprLoc);
3348
3349 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3350 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003351 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003352}
3353
Anders Carlsson1b00e242010-04-23 03:10:23 +00003354/// ImplicitInitializerKind - How an implicit base or member initializer should
3355/// initialize its base or member.
3356enum ImplicitInitializerKind {
3357 IIK_Default,
3358 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003359 IIK_Move,
3360 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003361};
3362
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003363static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003364BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003365 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003366 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003367 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003368 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003369 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003370 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3371 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003372
John McCalldadc5752010-08-24 06:29:42 +00003373 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003374
3375 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003376 case IIK_Inherit: {
3377 const CXXRecordDecl *Inherited =
3378 Constructor->getInheritedConstructor()->getParent();
3379 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3380 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3381 // C++11 [class.inhctor]p8:
3382 // Each expression in the expression-list is of the form
3383 // static_cast<T&&>(p), where p is the name of the corresponding
3384 // constructor parameter and T is the declared type of p.
3385 SmallVector<Expr*, 16> Args;
3386 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3387 ParmVarDecl *PD = Constructor->getParamDecl(I);
3388 ExprResult ArgExpr =
3389 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3390 VK_LValue, SourceLocation());
3391 if (ArgExpr.isInvalid())
3392 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003393 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003394 }
3395
3396 InitializationKind InitKind = InitializationKind::CreateDirect(
3397 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003398 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003399 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3400 break;
3401 }
3402 }
3403 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003404 case IIK_Default: {
3405 InitializationKind InitKind
3406 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003407 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3408 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003409 break;
3410 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003411
Sebastian Redl22653ba2011-08-30 19:58:05 +00003412 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003413 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003414 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003415 ParmVarDecl *Param = Constructor->getParamDecl(0);
3416 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003417
Anders Carlsson1b00e242010-04-23 03:10:23 +00003418 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003419 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003420 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003421 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003423
Eli Friedmanfa0df832012-02-02 03:46:19 +00003424 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3425
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003426 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003427 QualType ArgTy =
3428 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3429 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003430
Sebastian Redl22653ba2011-08-30 19:58:05 +00003431 if (Moving) {
3432 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3433 }
3434
John McCallcf142162010-08-07 06:22:56 +00003435 CXXCastPath BasePath;
3436 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003437 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3438 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003439 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003440 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003441
Anders Carlsson1b00e242010-04-23 03:10:23 +00003442 InitializationKind InitKind
3443 = InitializationKind::CreateDirect(Constructor->getLocation(),
3444 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003445 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3446 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003447 break;
3448 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003449 }
John McCallb268a282010-08-23 23:25:46 +00003450
Douglas Gregora40433a2010-12-07 00:41:46 +00003451 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003452 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003453 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003454
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003455 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003456 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003457 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3458 SourceLocation()),
3459 BaseSpec->isVirtual(),
3460 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003461 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003462 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003463 SourceLocation());
3464
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003465 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003466}
3467
Sebastian Redl22653ba2011-08-30 19:58:05 +00003468static bool RefersToRValueRef(Expr *MemRef) {
3469 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3470 return Referenced->getType()->isRValueReferenceType();
3471}
3472
Anders Carlsson3c1db572010-04-23 02:15:47 +00003473static bool
3474BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003475 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003476 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003477 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003478 if (Field->isInvalidDecl())
3479 return true;
3480
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003481 SourceLocation Loc = Constructor->getLocation();
3482
Sebastian Redl22653ba2011-08-30 19:58:05 +00003483 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3484 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003485 ParmVarDecl *Param = Constructor->getParamDecl(0);
3486 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003487
3488 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003489 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3490 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003491
Anders Carlsson423f5d82010-04-23 16:04:08 +00003492 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003493 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003494 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003495 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003496
Eli Friedmanfa0df832012-02-02 03:46:19 +00003497 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3498
Sebastian Redl22653ba2011-08-30 19:58:05 +00003499 if (Moving) {
3500 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3501 }
3502
Douglas Gregor94f9a482010-05-05 05:51:00 +00003503 // Build a reference to this field within the parameter.
3504 CXXScopeSpec SS;
3505 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3506 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003507 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3508 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003509 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003510 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003511 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003512 ParamType, Loc,
3513 /*IsArrow=*/false,
3514 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003515 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003516 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003517 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003518 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003519 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003520 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003521
3522 // C++11 [class.copy]p15:
3523 // - if a member m has rvalue reference type T&&, it is direct-initialized
3524 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003525 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003526 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003527 }
3528
Douglas Gregor94f9a482010-05-05 05:51:00 +00003529 // When the field we are copying is an array, create index variables for
3530 // each dimension of the array. We use these index variables to subscript
3531 // the source array, and other clients (e.g., CodeGen) will perform the
3532 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003533 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003534 QualType BaseType = Field->getType();
3535 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003536 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003537 while (const ConstantArrayType *Array
3538 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003539 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003540 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003541 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003542 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003543 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003544 llvm::raw_svector_ostream OS(Str);
3545 OS << "__i" << IndexVariables.size();
3546 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3547 }
3548 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003549 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003550 IterationVarName, SizeType,
3551 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003552 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003553 IndexVariables.push_back(IterationVar);
3554
3555 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003556 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003557 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003558 assert(!IterationVarRef.isInvalid() &&
3559 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003561 assert(!IterationVarRef.isInvalid() &&
3562 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003563
Douglas Gregor94f9a482010-05-05 05:51:00 +00003564 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003565 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3566 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003567 Loc);
3568 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003569 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003570
Douglas Gregor94f9a482010-05-05 05:51:00 +00003571 BaseType = Array->getElementType();
3572 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003573
3574 // The array subscript expression is an lvalue, which is wrong for moving.
3575 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003576 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003577
Douglas Gregor94f9a482010-05-05 05:51:00 +00003578 // Construct the entity that we will be initializing. For an array, this
3579 // will be first element in the array, which may require several levels
3580 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003581 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003582 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003583 if (Indirect)
3584 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3585 else
3586 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003587 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3588 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3589 0,
3590 Entities.back()));
3591
3592 // Direct-initialize to use the copy constructor.
3593 InitializationKind InitKind =
3594 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3595
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003596 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003597 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003598
John McCalldadc5752010-08-24 06:29:42 +00003599 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003600 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003601 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003602 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003603 if (MemberInit.isInvalid())
3604 return true;
3605
Douglas Gregor493627b2011-08-10 15:22:55 +00003606 if (Indirect) {
3607 assert(IndexVariables.size() == 0 &&
3608 "Indirect field improperly initialized");
3609 CXXMemberInit
3610 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3611 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003612 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003613 Loc);
3614 } else
3615 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003616 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003617 Loc,
3618 IndexVariables.data(),
3619 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003620 return false;
3621 }
3622
Richard Smithc2bc61b2013-03-18 21:12:30 +00003623 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3624 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003625
Anders Carlsson3c1db572010-04-23 02:15:47 +00003626 QualType FieldBaseElementType =
3627 SemaRef.Context.getBaseElementType(Field->getType());
3628
Anders Carlsson3c1db572010-04-23 02:15:47 +00003629 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003630 InitializedEntity InitEntity
3631 = Indirect? InitializedEntity::InitializeMember(Indirect)
3632 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003633 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003634 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003635
3636 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3637 ExprResult MemberInit =
3638 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003639
Douglas Gregora40433a2010-12-07 00:41:46 +00003640 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003641 if (MemberInit.isInvalid())
3642 return true;
3643
Douglas Gregor493627b2011-08-10 15:22:55 +00003644 if (Indirect)
3645 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3646 Indirect, Loc,
3647 Loc,
3648 MemberInit.get(),
3649 Loc);
3650 else
3651 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3652 Field, Loc, Loc,
3653 MemberInit.get(),
3654 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003655 return false;
3656 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003657
Alexis Hunt8b455182011-05-17 00:19:05 +00003658 if (!Field->getParent()->isUnion()) {
3659 if (FieldBaseElementType->isReferenceType()) {
3660 SemaRef.Diag(Constructor->getLocation(),
3661 diag::err_uninitialized_member_in_ctor)
3662 << (int)Constructor->isImplicit()
3663 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3664 << 0 << Field->getDeclName();
3665 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3666 return true;
3667 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003668
Alexis Hunt8b455182011-05-17 00:19:05 +00003669 if (FieldBaseElementType.isConstQualified()) {
3670 SemaRef.Diag(Constructor->getLocation(),
3671 diag::err_uninitialized_member_in_ctor)
3672 << (int)Constructor->isImplicit()
3673 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3674 << 1 << Field->getDeclName();
3675 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3676 return true;
3677 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003678 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003679
David Blaikiebbafb8a2012-03-11 07:00:24 +00003680 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003681 FieldBaseElementType->isObjCRetainableType() &&
3682 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3683 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003684 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003685 // Default-initialize Objective-C pointers to NULL.
3686 CXXMemberInit
3687 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3688 Loc, Loc,
3689 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3690 Loc);
3691 return false;
3692 }
3693
Anders Carlsson3c1db572010-04-23 02:15:47 +00003694 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003695 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003696 return false;
3697}
John McCallbc83b3f2010-05-20 23:23:51 +00003698
3699namespace {
3700struct BaseAndFieldInfo {
3701 Sema &S;
3702 CXXConstructorDecl *Ctor;
3703 bool AnyErrorsInInits;
3704 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003705 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003706 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003707 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003708
3709 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3710 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003711 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3712 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003713 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003714 else if (Generated && Ctor->isMoveConstructor())
3715 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003716 else if (Ctor->getInheritedConstructor())
3717 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003718 else
3719 IIK = IIK_Default;
3720 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003721
3722 bool isImplicitCopyOrMove() const {
3723 switch (IIK) {
3724 case IIK_Copy:
3725 case IIK_Move:
3726 return true;
3727
3728 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003729 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003730 return false;
3731 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003732
3733 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003734 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003735
3736 bool addFieldInitializer(CXXCtorInitializer *Init) {
3737 AllToInit.push_back(Init);
3738
3739 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003740 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003741 S.UnusedPrivateFields.remove(Init->getAnyMember());
3742
3743 return false;
3744 }
John McCallbc83b3f2010-05-20 23:23:51 +00003745
Richard Smithab44d5b2013-12-10 08:25:00 +00003746 bool isInactiveUnionMember(FieldDecl *Field) {
3747 RecordDecl *Record = Field->getParent();
3748 if (!Record->isUnion())
3749 return false;
3750
Richard Smith8d183852013-12-10 20:56:03 +00003751 if (FieldDecl *Active =
3752 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003753 return Active != Field->getCanonicalDecl();
3754
3755 // In an implicit copy or move constructor, ignore any in-class initializer.
3756 if (isImplicitCopyOrMove())
3757 return true;
3758
3759 // If there's no explicit initialization, the field is active only if it
3760 // has an in-class initializer...
3761 if (Field->hasInClassInitializer())
3762 return false;
3763 // ... or it's an anonymous struct or union whose class has an in-class
3764 // initializer.
3765 if (!Field->isAnonymousStructOrUnion())
3766 return true;
3767 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3768 return !FieldRD->hasInClassInitializer();
3769 }
3770
3771 /// \brief Determine whether the given field is, or is within, a union member
3772 /// that is inactive (because there was an initializer given for a different
3773 /// member of the union, or because the union was not initialized at all).
3774 bool isWithinInactiveUnionMember(FieldDecl *Field,
3775 IndirectFieldDecl *Indirect) {
3776 if (!Indirect)
3777 return isInactiveUnionMember(Field);
3778
Aaron Ballman29c94602014-03-07 18:36:15 +00003779 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003780 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003781 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003782 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003783 }
3784 return false;
3785 }
3786};
Richard Smithc94ec842011-09-19 13:34:43 +00003787}
3788
Douglas Gregor10f939c2011-11-02 23:04:16 +00003789/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3790/// array type.
3791static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3792 if (T->isIncompleteArrayType())
3793 return true;
3794
3795 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3796 if (!ArrayT->getSize())
3797 return true;
3798
3799 T = ArrayT->getElementType();
3800 }
3801
3802 return false;
3803}
3804
Richard Smith938f40b2011-06-11 17:19:42 +00003805static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003806 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003807 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003808 if (Field->isInvalidDecl())
3809 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003810
Chandler Carruth139e9622010-06-30 02:59:29 +00003811 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003812 if (CXXCtorInitializer *Init =
3813 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003814 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003815
Richard Smithab44d5b2013-12-10 08:25:00 +00003816 // C++11 [class.base.init]p8:
3817 // if the entity is a non-static data member that has a
3818 // brace-or-equal-initializer and either
3819 // -- the constructor's class is a union and no other variant member of that
3820 // union is designated by a mem-initializer-id or
3821 // -- the constructor's class is not a union, and, if the entity is a member
3822 // of an anonymous union, no other member of that union is designated by
3823 // a mem-initializer-id,
3824 // the entity is initialized as specified in [dcl.init].
3825 //
3826 // We also apply the same rules to handle anonymous structs within anonymous
3827 // unions.
3828 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3829 return false;
3830
Douglas Gregor7db3e952011-11-28 20:03:15 +00003831 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003832 ExprResult DIE =
3833 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3834 if (DIE.isInvalid())
3835 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003836 CXXCtorInitializer *Init;
3837 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003838 Init = new (SemaRef.Context)
3839 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3840 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003841 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003842 Init = new (SemaRef.Context)
3843 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3844 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003845 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003846 }
3847
Douglas Gregor10f939c2011-11-02 23:04:16 +00003848 // Don't initialize incomplete or zero-length arrays.
3849 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3850 return false;
3851
John McCallbc83b3f2010-05-20 23:23:51 +00003852 // Don't try to build an implicit initializer if there were semantic
3853 // errors in any of the initializers (and therefore we might be
3854 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003855 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003856 return false;
3857
Craig Topperc3ec1492014-05-26 06:22:03 +00003858 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003859 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3860 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003861 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003862
Richard Smith0a8cfc72012-08-07 21:30:42 +00003863 if (!Init)
3864 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003865
Richard Smith0a8cfc72012-08-07 21:30:42 +00003866 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003867}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003868
3869bool
3870Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3871 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003872 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003873 Constructor->setNumCtorInitializers(1);
3874 CXXCtorInitializer **initializer =
3875 new (Context) CXXCtorInitializer*[1];
3876 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3877 Constructor->setCtorInitializers(initializer);
3878
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003879 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003880 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003881 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3882 }
3883
Alexis Hunte2622992011-05-05 00:05:47 +00003884 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003885
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003886 DiagnoseUninitializedFields(*this, Constructor);
3887
Alexis Hunt61bc1732011-05-01 07:04:31 +00003888 return false;
3889}
Douglas Gregor493627b2011-08-10 15:22:55 +00003890
David Blaikie3fc2f912013-01-17 05:26:25 +00003891bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3892 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003893 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003894 // Just store the initializers as written, they will be checked during
3895 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003896 if (!Initializers.empty()) {
3897 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003898 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003899 new (Context) CXXCtorInitializer*[Initializers.size()];
3900 memcpy(baseOrMemberInitializers, Initializers.data(),
3901 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003902 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003903 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003904
3905 // Let template instantiation know whether we had errors.
3906 if (AnyErrors)
3907 Constructor->setInvalidDecl();
3908
Anders Carlssondb0a9652010-04-02 06:26:44 +00003909 return false;
3910 }
3911
John McCallbc83b3f2010-05-20 23:23:51 +00003912 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003913
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003914 // We need to build the initializer AST according to order of construction
3915 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003916 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003917 if (!ClassDecl)
3918 return true;
3919
Eli Friedman9cf6b592009-11-09 19:20:36 +00003920 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003921
David Blaikie3fc2f912013-01-17 05:26:25 +00003922 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003923 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003924
Anders Carlssondb0a9652010-04-02 06:26:44 +00003925 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003926 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003927 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003928 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003929
3930 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003931 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003932 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003933 if (FD && FD->getParent()->isUnion())
3934 Info.ActiveUnionMember.insert(std::make_pair(
3935 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3936 }
3937 } else if (FieldDecl *FD = Member->getMember()) {
3938 if (FD->getParent()->isUnion())
3939 Info.ActiveUnionMember.insert(std::make_pair(
3940 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3941 }
3942 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003943 }
3944
Anders Carlsson43c64af2010-04-21 19:52:01 +00003945 // Keep track of the direct virtual bases.
3946 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003947 for (auto &I : ClassDecl->bases()) {
3948 if (I.isVirtual())
3949 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003950 }
3951
Anders Carlssondb0a9652010-04-02 06:26:44 +00003952 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003953 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003954 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003955 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003956 // [class.base.init]p7, per DR257:
3957 // A mem-initializer where the mem-initializer-id names a virtual base
3958 // class is ignored during execution of a constructor of any class that
3959 // is not the most derived class.
3960 if (ClassDecl->isAbstract()) {
3961 // FIXME: Provide a fixit to remove the base specifier. This requires
3962 // tracking the location of the associated comma for a base specifier.
3963 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003964 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003965 DiagnoseAbstractType(ClassDecl);
3966 }
3967
John McCallbc83b3f2010-05-20 23:23:51 +00003968 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003969 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3970 // [class.base.init]p8, per DR257:
3971 // If a given [...] base class is not named by a mem-initializer-id
3972 // [...] and the entity is not a virtual base class of an abstract
3973 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003974 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003975 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003976 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003977 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003978 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003979 HadError = true;
3980 continue;
3981 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003982
John McCallbc83b3f2010-05-20 23:23:51 +00003983 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003984 }
3985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
John McCallbc83b3f2010-05-20 23:23:51 +00003987 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003988 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003989 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003990 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003991 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003992
Alexis Hunt1d792652011-01-08 20:30:50 +00003993 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003994 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003995 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003996 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003997 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003998 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003999 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004000 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004001 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004002 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004003 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004004
John McCallbc83b3f2010-05-20 23:23:51 +00004005 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004006 }
4007 }
Mike Stump11289f42009-09-09 15:08:12 +00004008
John McCallbc83b3f2010-05-20 23:23:51 +00004009 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004010 for (auto *Mem : ClassDecl->decls()) {
4011 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004012 // C++ [class.bit]p2:
4013 // A declaration for a bit-field that omits the identifier declares an
4014 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4015 // initialized.
4016 if (F->isUnnamedBitfield())
4017 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004018
Sebastian Redl22653ba2011-08-30 19:58:05 +00004019 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004020 // handle anonymous struct/union fields based on their individual
4021 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004022 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004023 continue;
4024
4025 if (CollectFieldInitializer(*this, Info, F))
4026 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004027 continue;
4028 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004029
4030 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004031 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004032 continue;
4033
Aaron Ballman629afae2014-03-07 19:56:05 +00004034 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004035 if (F->getType()->isIncompleteArrayType()) {
4036 assert(ClassDecl->hasFlexibleArrayMember() &&
4037 "Incomplete array type is not valid");
4038 continue;
4039 }
4040
Douglas Gregor493627b2011-08-10 15:22:55 +00004041 // Initialize each field of an anonymous struct individually.
4042 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4043 HadError = true;
4044
4045 continue;
4046 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048
David Blaikie3fc2f912013-01-17 05:26:25 +00004049 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004050 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004051 Constructor->setNumCtorInitializers(NumInitializers);
4052 CXXCtorInitializer **baseOrMemberInitializers =
4053 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004054 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004055 NumInitializers * sizeof(CXXCtorInitializer*));
4056 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004057
John McCalla6309952010-03-16 21:39:52 +00004058 // Constructors implicitly reference the base and member
4059 // destructors.
4060 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4061 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004062 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004063
4064 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004065}
4066
David Blaikieb61b8152013-01-17 08:49:22 +00004067static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004068 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004069 const RecordDecl *RD = RT->getDecl();
4070 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004071 for (auto *Field : RD->fields())
4072 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004073 return;
4074 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004075 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004076 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004077}
4078
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004079static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4080 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004081}
4082
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004083static const void *GetKeyForMember(ASTContext &Context,
4084 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004085 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004086 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004087
Richard Smithcd45dbc2014-04-19 03:48:30 +00004088 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004089}
4090
David Blaikie3fc2f912013-01-17 05:26:25 +00004091static void DiagnoseBaseOrMemInitializerOrder(
4092 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4093 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004094 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004095 return;
Mike Stump11289f42009-09-09 15:08:12 +00004096
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004097 // Don't check initializers order unless the warning is enabled at the
4098 // location of at least one initializer.
4099 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004100 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004101 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004102 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4103 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004104 ShouldCheckOrder = true;
4105 break;
4106 }
4107 }
4108 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004109 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004110
John McCallbb7b6582010-04-10 07:37:23 +00004111 // Build the list of bases and members in the order that they'll
4112 // actually be initialized. The explicit initializers should be in
4113 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004114 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004115
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004116 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4117
John McCallbb7b6582010-04-10 07:37:23 +00004118 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004119 for (const auto &VBase : ClassDecl->vbases())
4120 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004121
John McCallbb7b6582010-04-10 07:37:23 +00004122 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004123 for (const auto &Base : ClassDecl->bases()) {
4124 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004125 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004126 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004127 }
Mike Stump11289f42009-09-09 15:08:12 +00004128
John McCallbb7b6582010-04-10 07:37:23 +00004129 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004130 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004131 if (Field->isUnnamedBitfield())
4132 continue;
4133
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004134 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004135 }
4136
John McCallbb7b6582010-04-10 07:37:23 +00004137 unsigned NumIdealInits = IdealInitKeys.size();
4138 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004139
Craig Topperc3ec1492014-05-26 06:22:03 +00004140 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004141 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004142 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004143 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004144
4145 // Scan forward to try to find this initializer in the idealized
4146 // initializers list.
4147 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4148 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004149 break;
John McCallbb7b6582010-04-10 07:37:23 +00004150
4151 // If we didn't find this initializer, it must be because we
4152 // scanned past it on a previous iteration. That can only
4153 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004154 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004155 Sema::SemaDiagnosticBuilder D =
4156 SemaRef.Diag(PrevInit->getSourceLocation(),
4157 diag::warn_initializer_out_of_order);
4158
Francois Pichetd583da02010-12-04 09:14:42 +00004159 if (PrevInit->isAnyMemberInitializer())
4160 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004161 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004162 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004163
Francois Pichetd583da02010-12-04 09:14:42 +00004164 if (Init->isAnyMemberInitializer())
4165 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004166 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004167 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004168
4169 // Move back to the initializer's location in the ideal list.
4170 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4171 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004172 break;
John McCallbb7b6582010-04-10 07:37:23 +00004173
4174 assert(IdealIndex != NumIdealInits &&
4175 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004176 }
John McCallbb7b6582010-04-10 07:37:23 +00004177
4178 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004179 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004180}
4181
John McCall23eebd92010-04-10 09:28:51 +00004182namespace {
4183bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004184 CXXCtorInitializer *Init,
4185 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004186 if (!PrevInit) {
4187 PrevInit = Init;
4188 return false;
4189 }
4190
Douglas Gregorea306a12013-03-25 23:28:23 +00004191 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004192 S.Diag(Init->getSourceLocation(),
4193 diag::err_multiple_mem_initialization)
4194 << Field->getDeclName()
4195 << Init->getSourceRange();
4196 else {
John McCall424cec92011-01-19 06:33:43 +00004197 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004198 assert(BaseClass && "neither field nor base");
4199 S.Diag(Init->getSourceLocation(),
4200 diag::err_multiple_base_initialization)
4201 << QualType(BaseClass, 0)
4202 << Init->getSourceRange();
4203 }
4204 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4205 << 0 << PrevInit->getSourceRange();
4206
4207 return true;
4208}
4209
Alexis Hunt1d792652011-01-08 20:30:50 +00004210typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004211typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4212
4213bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004214 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004215 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004216 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004217 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004218 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004219
4220 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004221 if (Parent->isUnion()) {
4222 UnionEntry &En = Unions[Parent];
4223 if (En.first && En.first != Child) {
4224 S.Diag(Init->getSourceLocation(),
4225 diag::err_multiple_mem_union_initialization)
4226 << Field->getDeclName()
4227 << Init->getSourceRange();
4228 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4229 << 0 << En.second->getSourceRange();
4230 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004231 }
4232 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004233 En.first = Child;
4234 En.second = Init;
4235 }
David Blaikie0f65d592011-11-17 06:01:57 +00004236 if (!Parent->isAnonymousStructOrUnion())
4237 return false;
John McCall23eebd92010-04-10 09:28:51 +00004238 }
4239
4240 Child = Parent;
4241 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004242 }
John McCall23eebd92010-04-10 09:28:51 +00004243
4244 return false;
4245}
4246}
4247
Anders Carlssone857b292010-04-02 03:37:03 +00004248/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004249void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004250 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004251 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004252 bool AnyErrors) {
4253 if (!ConstructorDecl)
4254 return;
4255
4256 AdjustDeclIfTemplate(ConstructorDecl);
4257
4258 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004259 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004260
4261 if (!Constructor) {
4262 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4263 return;
4264 }
4265
John McCall23eebd92010-04-10 09:28:51 +00004266 // Mapping for the duplicate initializers check.
4267 // For member initializers, this is keyed with a FieldDecl*.
4268 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004269 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004270
4271 // Mapping for the inconsistent anonymous-union initializers check.
4272 RedundantUnionMap MemberUnions;
4273
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004274 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004275 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004276 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004277
Abramo Bagnara341d7832010-05-26 18:09:23 +00004278 // Set the source order index.
4279 Init->setSourceOrder(i);
4280
Francois Pichetd583da02010-12-04 09:14:42 +00004281 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004282 const void *Key = GetKeyForMember(Context, Init);
4283 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004284 CheckRedundantUnionInit(*this, Init, MemberUnions))
4285 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004286 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004287 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004288 if (CheckRedundantInit(*this, Init, Members[Key]))
4289 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004290 } else {
4291 assert(Init->isDelegatingInitializer());
4292 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004293 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004294 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004295 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004296 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004297 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004298 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004299 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004300 // Return immediately as the initializer is set.
4301 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004302 }
Anders Carlssone857b292010-04-02 03:37:03 +00004303 }
4304
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004305 if (HadError)
4306 return;
4307
David Blaikie3fc2f912013-01-17 05:26:25 +00004308 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004309
David Blaikie3fc2f912013-01-17 05:26:25 +00004310 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004311
Richard Trieuef64e942013-10-25 00:56:00 +00004312 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004313}
4314
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004315void
John McCalla6309952010-03-16 21:39:52 +00004316Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4317 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004318 // Ignore dependent contexts. Also ignore unions, since their members never
4319 // have destructors implicitly called.
4320 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004321 return;
John McCall1064d7e2010-03-16 05:22:47 +00004322
4323 // FIXME: all the access-control diagnostics are positioned on the
4324 // field/base declaration. That's probably good; that said, the
4325 // user might reasonably want to know why the destructor is being
4326 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004327
Anders Carlssondee9a302009-11-17 04:44:12 +00004328 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004329 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004330 if (Field->isInvalidDecl())
4331 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004332
4333 // Don't destroy incomplete or zero-length arrays.
4334 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4335 continue;
4336
Anders Carlssondee9a302009-11-17 04:44:12 +00004337 QualType FieldType = Context.getBaseElementType(Field->getType());
4338
4339 const RecordType* RT = FieldType->getAs<RecordType>();
4340 if (!RT)
4341 continue;
4342
4343 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004344 if (FieldClassDecl->isInvalidDecl())
4345 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004346 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004347 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004348 // The destructor for an implicit anonymous union member is never invoked.
4349 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4350 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004351
Douglas Gregore71edda2010-07-01 22:47:18 +00004352 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004353 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004354 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004355 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004356 << Field->getDeclName()
4357 << FieldType);
4358
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004359 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004360 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004361 }
4362
John McCall1064d7e2010-03-16 05:22:47 +00004363 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4364
Anders Carlssondee9a302009-11-17 04:44:12 +00004365 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004366 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004367 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004368 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004369
4370 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004371 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004372 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004373
John McCall1064d7e2010-03-16 05:22:47 +00004374 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004375 // If our base class is invalid, we probably can't get its dtor anyway.
4376 if (BaseClassDecl->isInvalidDecl())
4377 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004378 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004379 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004380
Douglas Gregore71edda2010-07-01 22:47:18 +00004381 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004382 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004383
4384 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004385 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004386 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004387 << Base.getType()
4388 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004389 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004390
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004391 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004392 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004393 }
4394
4395 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004396 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004397 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004398 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004399
4400 // Ignore direct virtual bases.
4401 if (DirectVirtualBases.count(RT))
4402 continue;
4403
John McCall1064d7e2010-03-16 05:22:47 +00004404 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004405 // If our base class is invalid, we probably can't get its dtor anyway.
4406 if (BaseClassDecl->isInvalidDecl())
4407 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004408 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004409 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004410
Douglas Gregore71edda2010-07-01 22:47:18 +00004411 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004412 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004413 if (CheckDestructorAccess(
4414 ClassDecl->getLocation(), Dtor,
4415 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004416 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004417 Context.getTypeDeclType(ClassDecl)) ==
4418 AR_accessible) {
4419 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004420 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004421 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004422 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004423 }
John McCall1064d7e2010-03-16 05:22:47 +00004424
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004425 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004426 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004427 }
4428}
4429
John McCall48871652010-08-21 09:40:31 +00004430void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004431 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004432 return;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Mike Stump11289f42009-09-09 15:08:12 +00004434 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004435 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004436 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004437 DiagnoseUninitializedFields(*this, Constructor);
4438 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004439}
4440
Mike Stump11289f42009-09-09 15:08:12 +00004441bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004442 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004443 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4444 unsigned DiagID;
4445 AbstractDiagSelID SelID;
4446
4447 public:
4448 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4449 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004450
Craig Toppera798a9d2014-03-02 09:32:10 +00004451 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004452 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004453 if (SelID == -1)
4454 S.Diag(Loc, DiagID) << T;
4455 else
4456 S.Diag(Loc, DiagID) << SelID << T;
4457 }
4458 } Diagnoser(DiagID, SelID);
4459
4460 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004461}
4462
Anders Carlssoneabf7702009-08-27 00:13:57 +00004463bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004464 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004465 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004466 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004467
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004468 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004469 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004470
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004471 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004472 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004473 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004474 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004475
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004476 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004477 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004478 }
Mike Stump11289f42009-09-09 15:08:12 +00004479
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004480 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004481 if (!RT)
4482 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004483
John McCall67da35c2010-02-04 22:26:26 +00004484 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004485
John McCall02db245d2010-08-18 09:41:07 +00004486 // We can't answer whether something is abstract until it has a
4487 // definition. If it's currently being defined, we'll walk back
4488 // over all the declarations when we have a full definition.
4489 const CXXRecordDecl *Def = RD->getDefinition();
4490 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004491 return false;
4492
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004493 if (!RD->isAbstract())
4494 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004495
Douglas Gregorae298422012-05-04 17:09:59 +00004496 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004497 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004498
John McCall02db245d2010-08-18 09:41:07 +00004499 return true;
4500}
4501
4502void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4503 // Check if we've already emitted the list of pure virtual functions
4504 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004505 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004506 return;
Mike Stump11289f42009-09-09 15:08:12 +00004507
Richard Smithbc46e432013-07-22 02:56:56 +00004508 // If the diagnostic is suppressed, don't emit the notes. We're only
4509 // going to emit them once, so try to attach them to a diagnostic we're
4510 // actually going to show.
4511 if (Diags.isLastDiagnosticIgnored())
4512 return;
4513
Douglas Gregor4165bd62010-03-23 23:47:56 +00004514 CXXFinalOverriderMap FinalOverriders;
4515 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004516
Anders Carlssona2f74f32010-06-03 01:00:02 +00004517 // Keep a set of seen pure methods so we won't diagnose the same method
4518 // more than once.
4519 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4520
Douglas Gregor4165bd62010-03-23 23:47:56 +00004521 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4522 MEnd = FinalOverriders.end();
4523 M != MEnd;
4524 ++M) {
4525 for (OverridingMethods::iterator SO = M->second.begin(),
4526 SOEnd = M->second.end();
4527 SO != SOEnd; ++SO) {
4528 // C++ [class.abstract]p4:
4529 // A class is abstract if it contains or inherits at least one
4530 // pure virtual function for which the final overrider is pure
4531 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004532
Douglas Gregor4165bd62010-03-23 23:47:56 +00004533 //
4534 if (SO->second.size() != 1)
4535 continue;
4536
4537 if (!SO->second.front().Method->isPure())
4538 continue;
4539
David Blaikie82e95a32014-11-19 07:49:47 +00004540 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004541 continue;
4542
Douglas Gregor4165bd62010-03-23 23:47:56 +00004543 Diag(SO->second.front().Method->getLocation(),
4544 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004545 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004546 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004547 }
4548
4549 if (!PureVirtualClassDiagSet)
4550 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4551 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004552}
4553
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004554namespace {
John McCall02db245d2010-08-18 09:41:07 +00004555struct AbstractUsageInfo {
4556 Sema &S;
4557 CXXRecordDecl *Record;
4558 CanQualType AbstractType;
4559 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall02db245d2010-08-18 09:41:07 +00004561 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4562 : S(S), Record(Record),
4563 AbstractType(S.Context.getCanonicalType(
4564 S.Context.getTypeDeclType(Record))),
4565 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004566
John McCall02db245d2010-08-18 09:41:07 +00004567 void DiagnoseAbstractType() {
4568 if (Invalid) return;
4569 S.DiagnoseAbstractType(Record);
4570 Invalid = true;
4571 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004572
John McCall02db245d2010-08-18 09:41:07 +00004573 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4574};
4575
4576struct CheckAbstractUsage {
4577 AbstractUsageInfo &Info;
4578 const NamedDecl *Ctx;
4579
4580 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4581 : Info(Info), Ctx(Ctx) {}
4582
4583 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4584 switch (TL.getTypeLocClass()) {
4585#define ABSTRACT_TYPELOC(CLASS, PARENT)
4586#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004587 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004588#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004589 }
John McCall02db245d2010-08-18 09:41:07 +00004590 }
Mike Stump11289f42009-09-09 15:08:12 +00004591
John McCall02db245d2010-08-18 09:41:07 +00004592 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004593 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004594 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4595 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004596 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004597
4598 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004599 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004600 }
John McCall02db245d2010-08-18 09:41:07 +00004601 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004602
John McCall02db245d2010-08-18 09:41:07 +00004603 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4604 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
John McCall02db245d2010-08-18 09:41:07 +00004607 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4608 // Visit the type parameters from a permissive context.
4609 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4610 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4611 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4612 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4613 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4614 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004615 }
John McCall02db245d2010-08-18 09:41:07 +00004616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617
John McCall02db245d2010-08-18 09:41:07 +00004618 // Visit pointee types from a permissive context.
4619#define CheckPolymorphic(Type) \
4620 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4621 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4622 }
4623 CheckPolymorphic(PointerTypeLoc)
4624 CheckPolymorphic(ReferenceTypeLoc)
4625 CheckPolymorphic(MemberPointerTypeLoc)
4626 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004627 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004628
John McCall02db245d2010-08-18 09:41:07 +00004629 /// Handle all the types we haven't given a more specific
4630 /// implementation for above.
4631 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4632 // Every other kind of type that we haven't called out already
4633 // that has an inner type is either (1) sugar or (2) contains that
4634 // inner type in some way as a subobject.
4635 if (TypeLoc Next = TL.getNextTypeLoc())
4636 return Visit(Next, Sel);
4637
4638 // If there's no inner type and we're in a permissive context,
4639 // don't diagnose.
4640 if (Sel == Sema::AbstractNone) return;
4641
4642 // Check whether the type matches the abstract type.
4643 QualType T = TL.getType();
4644 if (T->isArrayType()) {
4645 Sel = Sema::AbstractArrayType;
4646 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004647 }
John McCall02db245d2010-08-18 09:41:07 +00004648 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4649 if (CT != Info.AbstractType) return;
4650
4651 // It matched; do some magic.
4652 if (Sel == Sema::AbstractArrayType) {
4653 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4654 << T << TL.getSourceRange();
4655 } else {
4656 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4657 << Sel << T << TL.getSourceRange();
4658 }
4659 Info.DiagnoseAbstractType();
4660 }
4661};
4662
4663void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4664 Sema::AbstractDiagSelID Sel) {
4665 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4666}
4667
4668}
4669
4670/// Check for invalid uses of an abstract type in a method declaration.
4671static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4672 CXXMethodDecl *MD) {
4673 // No need to do the check on definitions, which require that
4674 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004675 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004676 return;
4677
4678 // For safety's sake, just ignore it if we don't have type source
4679 // information. This should never happen for non-implicit methods,
4680 // but...
4681 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4682 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4683}
4684
4685/// Check for invalid uses of an abstract type within a class definition.
4686static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4687 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004688 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004689 if (D->isImplicit()) continue;
4690
4691 // Methods and method templates.
4692 if (isa<CXXMethodDecl>(D)) {
4693 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4694 } else if (isa<FunctionTemplateDecl>(D)) {
4695 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4696 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4697
4698 // Fields and static variables.
4699 } else if (isa<FieldDecl>(D)) {
4700 FieldDecl *FD = cast<FieldDecl>(D);
4701 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4702 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4703 } else if (isa<VarDecl>(D)) {
4704 VarDecl *VD = cast<VarDecl>(D);
4705 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4706 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4707
4708 // Nested classes and class templates.
4709 } else if (isa<CXXRecordDecl>(D)) {
4710 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4711 } else if (isa<ClassTemplateDecl>(D)) {
4712 CheckAbstractClassUsage(Info,
4713 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4714 }
4715 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004716}
4717
Hans Wennborg853ae942014-05-30 16:59:42 +00004718/// \brief Check class-level dllimport/dllexport attribute.
4719static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4720 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004721
4722 // MSVC inherits DLL attributes to partial class template specializations.
4723 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4724 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4725 if (Attr *TemplateAttr =
4726 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4727 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4728 A->setInherited(true);
4729 ClassAttr = A;
4730 }
4731 }
4732 }
4733
Hans Wennborg853ae942014-05-30 16:59:42 +00004734 if (!ClassAttr)
4735 return;
4736
Hans Wennborg8313c762014-11-03 16:09:16 +00004737 if (!Class->isExternallyVisible()) {
4738 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4739 << Class << ClassAttr;
4740 return;
4741 }
4742
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004743 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4744 !ClassAttr->isInherited()) {
4745 // Diagnose dll attributes on members of class with dll attribute.
4746 for (Decl *Member : Class->decls()) {
4747 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4748 continue;
4749 InheritableAttr *MemberAttr = getDLLAttr(Member);
4750 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4751 continue;
4752
4753 S.Diag(MemberAttr->getLocation(),
4754 diag::err_attribute_dll_member_of_dll_class)
4755 << MemberAttr << ClassAttr;
4756 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4757 Member->setInvalidDecl();
4758 }
4759 }
4760
4761 if (Class->getDescribedClassTemplate())
4762 // Don't inherit dll attribute until the template is instantiated.
4763 return;
4764
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004765 // The class is either imported or exported.
4766 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4767 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004768
Hans Wennborgfd76d912015-01-15 21:18:30 +00004769 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4770
4771 // Don't dllexport explicit class template instantiation declarations.
4772 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4773 Class->dropAttr<DLLExportAttr>();
4774 return;
4775 }
4776
Hans Wennborg853ae942014-05-30 16:59:42 +00004777 // Force declaration of implicit members so they can inherit the attribute.
4778 S.ForceDeclarationOfImplicitMembers(Class);
4779
4780 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4781 // seem to be true in practice?
4782
Hans Wennborg853ae942014-05-30 16:59:42 +00004783 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004784 VarDecl *VD = dyn_cast<VarDecl>(Member);
4785 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4786
4787 // Only methods and static fields inherit the attributes.
4788 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004789 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004790
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004791 if (MD) {
4792 // Don't process deleted methods.
4793 if (MD->isDeleted())
4794 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004795
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004796 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4797 // Current MSVC versions don't export the move assignment operators, so
4798 // don't attempt to import them if we have a definition.
4799 continue;
4800 }
4801
4802 if (MD->isInlined() && ClassImported &&
4803 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4804 // MinGW does not import inline functions.
4805 continue;
4806 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004807 }
4808
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004809 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004810 auto *NewAttr =
4811 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4812 NewAttr->setInherited(true);
4813 Member->addAttr(NewAttr);
4814 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004815
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004816 if (MD && ClassExported) {
4817 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004818 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004819
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004820 // .. except for certain kinds of template specializations.
4821 if (TSK == TSK_ExplicitInstantiationDeclaration)
4822 continue;
4823 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4824 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004825
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004826 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004827
4828 // The function will be passed to the consumer when its definition is
4829 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004830 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4831 MD->isCopyAssignmentOperator() ||
4832 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004833 // Synthesize and instantiate non-trivial implicit methods, explicitly
4834 // defaulted methods, and the copy and move assignment operators. The
4835 // latter are exported even if they are trivial, because the address of
4836 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004837 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004838
4839 // There is no later point when we will see the definition of this
4840 // function, so pass it to the consumer now.
4841 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004842 }
4843 }
4844 }
4845}
4846
Douglas Gregorc99f1552009-12-03 18:33:45 +00004847/// \brief Perform semantic checks on a class definition that has been
4848/// completing, introducing implicitly-declared members, checking for
4849/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004850void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004851 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004852 return;
4853
John McCall02db245d2010-08-18 09:41:07 +00004854 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4855 AbstractUsageInfo Info(*this, Record);
4856 CheckAbstractClassUsage(Info, Record);
4857 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004858
4859 // If this is not an aggregate type and has no user-declared constructor,
4860 // complain about any non-static data members of reference or const scalar
4861 // type, since they will never get initializers.
4862 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004863 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4864 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004865 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004866 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004867 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004868 continue;
4869
Douglas Gregor454a5b62010-04-15 00:00:53 +00004870 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004871 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004872 if (!Complained) {
4873 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4874 << Record->getTagKind() << Record;
4875 Complained = true;
4876 }
4877
4878 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4879 << F->getType()->isReferenceType()
4880 << F->getDeclName();
4881 }
4882 }
4883 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004884
Anders Carlssone771e762011-01-25 18:08:22 +00004885 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004886 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004887
4888 if (Record->getIdentifier()) {
4889 // C++ [class.mem]p13:
4890 // If T is the name of a class, then each of the following shall have a
4891 // name different from T:
4892 // - every member of every anonymous union that is a member of class T.
4893 //
4894 // C++ [class.mem]p14:
4895 // In addition, if class T has a user-declared constructor (12.1), every
4896 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004897 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4898 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4899 ++I) {
4900 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004901 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4902 isa<IndirectFieldDecl>(D)) {
4903 Diag(D->getLocation(), diag::err_member_name_of_class)
4904 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004905 break;
4906 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004907 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004908 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004909
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004910 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004911 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004912 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004913 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4914 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004915 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4916 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4917 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004918
David Majnemera5433082013-10-18 00:33:31 +00004919 if (Record->isAbstract()) {
4920 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4921 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4922 << FA->isSpelledAsSealed();
4923 DiagnoseAbstractType(Record);
4924 }
David Blaikie348df502012-09-21 03:21:07 +00004925 }
4926
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004927 bool HasMethodWithOverrideControl = false,
4928 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004929 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004930 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004931 // See if a method overloads virtual methods in a base
4932 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004933 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004934 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004935 if (M->hasAttr<OverrideAttr>())
4936 HasMethodWithOverrideControl = true;
4937 else if (M->size_overridden_methods() > 0)
4938 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004939 // Check whether the explicitly-defaulted special members are valid.
4940 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004941 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004942
4943 // For an explicitly defaulted or deleted special member, we defer
4944 // determining triviality until the class is complete. That time is now!
4945 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004946 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004947 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004948 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004949
4950 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004951 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004952 }
4953 }
4954 }
4955 }
4956
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004957 if (HasMethodWithOverrideControl &&
4958 HasOverridingMethodWithoutOverrideControl) {
4959 // At least one method has the 'override' control declared.
4960 // Diagnose all other overridden methods which do not have 'override' specified on them.
4961 for (auto *M : Record->methods())
4962 DiagnoseAbsenceOfOverrideControl(M);
4963 }
Sebastian Redl08905022011-02-05 19:23:19 +00004964
John McCall95833f32014-02-27 20:30:49 +00004965 // ms_struct is a request to use the same ABI rules as MSVC. Check
4966 // whether this class uses any C++ features that are implemented
4967 // completely differently in MSVC, and if so, emit a diagnostic.
4968 // That diagnostic defaults to an error, but we allow projects to
4969 // map it down to a warning (or ignore it). It's a fairly common
4970 // practice among users of the ms_struct pragma to mass-annotate
4971 // headers, sweeping up a bunch of types that the project doesn't
4972 // really rely on MSVC-compatible layout for. We must therefore
4973 // support "ms_struct except for C++ stuff" as a secondary ABI.
4974 if (Record->isMsStruct(Context) &&
4975 (Record->isPolymorphic() || Record->getNumBases())) {
4976 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004977 }
4978
Richard Smithc2bc61b2013-03-18 21:12:30 +00004979 // Declare inheriting constructors. We do this eagerly here because:
4980 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004981 // constructors from different classes.
4982 // - The lazy declaration of the other implicit constructors is so as to not
4983 // waste space and performance on classes that are not meant to be
4984 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004985 // have inheriting constructors.
4986 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004987
4988 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004989}
4990
Richard Smith41c35d62013-11-27 03:39:20 +00004991/// Look up the special member function that would be called by a special
4992/// member function for a subobject of class type.
4993///
4994/// \param Class The class type of the subobject.
4995/// \param CSM The kind of special member function.
4996/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4997/// \param ConstRHS True if this is a copy operation with a const object
4998/// on its RHS, that is, if the argument to the outer special member
4999/// function is 'const' and this is not a field marked 'mutable'.
5000static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5001 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5002 unsigned FieldQuals, bool ConstRHS) {
5003 unsigned LHSQuals = 0;
5004 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5005 LHSQuals = FieldQuals;
5006
5007 unsigned RHSQuals = FieldQuals;
5008 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5009 RHSQuals = 0;
5010 else if (ConstRHS)
5011 RHSQuals |= Qualifiers::Const;
5012
5013 return S.LookupSpecialMember(Class, CSM,
5014 RHSQuals & Qualifiers::Const,
5015 RHSQuals & Qualifiers::Volatile,
5016 false,
5017 LHSQuals & Qualifiers::Const,
5018 LHSQuals & Qualifiers::Volatile);
5019}
5020
Richard Smithb5800092012-06-10 05:43:50 +00005021/// Is the special member function which would be selected to perform the
5022/// specified operation on the specified class type a constexpr constructor?
5023static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5024 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005025 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005026 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005027 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005028 if (!SMOR || !SMOR->getMethod())
5029 // A constructor we wouldn't select can't be "involved in initializing"
5030 // anything.
5031 return true;
5032 return SMOR->getMethod()->isConstexpr();
5033}
5034
5035/// Determine whether the specified special member function would be constexpr
5036/// if it were implicitly defined.
5037static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5038 Sema::CXXSpecialMember CSM,
5039 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005040 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005041 return false;
5042
5043 // C++11 [dcl.constexpr]p4:
5044 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005045 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005046 switch (CSM) {
5047 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005048 // Since default constructor lookup is essentially trivial (and cannot
5049 // involve, for instance, template instantiation), we compute whether a
5050 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5051 //
5052 // This is important for performance; we need to know whether the default
5053 // constructor is constexpr to determine whether the type is a literal type.
5054 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5055
Richard Smithb5800092012-06-10 05:43:50 +00005056 case Sema::CXXCopyConstructor:
5057 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005058 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005059 break;
5060
5061 case Sema::CXXCopyAssignment:
5062 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005063 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005064 return false;
5065 // In C++1y, we need to perform overload resolution.
5066 Ctor = false;
5067 break;
5068
Richard Smithb5800092012-06-10 05:43:50 +00005069 case Sema::CXXDestructor:
5070 case Sema::CXXInvalid:
5071 return false;
5072 }
5073
5074 // -- if the class is a non-empty union, or for each non-empty anonymous
5075 // union member of a non-union class, exactly one non-static data member
5076 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005077 //
5078 // If we squint, this is guaranteed, since exactly one non-static data member
5079 // will be initialized (if the constructor isn't deleted), we just don't know
5080 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005081 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005082 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005083
5084 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005085 if (Ctor && ClassDecl->getNumVBases())
5086 return false;
5087
5088 // C++1y [class.copy]p26:
5089 // -- [the class] is a literal type, and
5090 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005091 return false;
5092
5093 // -- every constructor involved in initializing [...] base class
5094 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005095 // -- the assignment operator selected to copy/move each direct base
5096 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005097 for (const auto &B : ClassDecl->bases()) {
5098 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005099 if (!BaseType) continue;
5100
5101 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005102 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005103 return false;
5104 }
5105
5106 // -- every constructor involved in initializing non-static data members
5107 // [...] shall be a constexpr constructor;
5108 // -- every non-static data member and base class sub-object shall be
5109 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005110 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005111 // thereof), the assignment operator selected to copy/move that member is
5112 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005113 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005114 if (F->isInvalidDecl())
5115 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005116 QualType BaseType = S.Context.getBaseElementType(F->getType());
5117 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005118 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005119 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5120 BaseType.getCVRQualifiers(),
5121 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005122 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005123 }
5124 }
5125
5126 // All OK, it's constexpr!
5127 return true;
5128}
5129
Richard Smithd3b5c9082012-07-27 04:22:15 +00005130static Sema::ImplicitExceptionSpecification
5131computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5132 switch (S.getSpecialMember(MD)) {
5133 case Sema::CXXDefaultConstructor:
5134 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5135 case Sema::CXXCopyConstructor:
5136 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5137 case Sema::CXXCopyAssignment:
5138 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5139 case Sema::CXXMoveConstructor:
5140 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5141 case Sema::CXXMoveAssignment:
5142 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5143 case Sema::CXXDestructor:
5144 return S.ComputeDefaultedDtorExceptionSpec(MD);
5145 case Sema::CXXInvalid:
5146 break;
5147 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005148 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5149 "only special members have implicit exception specs");
5150 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005151}
5152
Reid Kleckner78af0702013-08-27 23:08:25 +00005153static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5154 CXXMethodDecl *MD) {
5155 FunctionProtoType::ExtProtoInfo EPI;
5156
5157 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005158 EPI.ExceptionSpec.Type = EST_Unevaluated;
5159 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005160
5161 // Set the calling convention to the default for C++ instance methods.
5162 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5163 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5164 /*IsCXXMethod=*/true));
5165 return EPI;
5166}
5167
Richard Smithd3b5c9082012-07-27 04:22:15 +00005168void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5169 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5170 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5171 return;
5172
Richard Smith7f782272012-07-30 23:48:14 +00005173 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005174 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005175
Richard Smith7f782272012-07-30 23:48:14 +00005176 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005177 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005178
5179 // A user-provided destructor can be defined outside the class. When that
5180 // happens, be sure to update the exception specification on both
5181 // declarations.
5182 const FunctionProtoType *CanonicalFPT =
5183 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5184 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005185 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005186}
5187
Richard Smithb9e90b12012-05-15 04:39:51 +00005188void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5189 CXXRecordDecl *RD = MD->getParent();
5190 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005191
Richard Smithb9e90b12012-05-15 04:39:51 +00005192 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5193 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005194
5195 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005196 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005197 bool First = MD == MD->getCanonicalDecl();
5198
5199 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005200
5201 // C++11 [dcl.fct.def.default]p1:
5202 // A function that is explicitly defaulted shall
5203 // -- be a special member function (checked elsewhere),
5204 // -- have the same type (except for ref-qualifiers, and except that a
5205 // copy operation can take a non-const reference) as an implicit
5206 // declaration, and
5207 // -- not have default arguments.
5208 unsigned ExpectedParams = 1;
5209 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5210 ExpectedParams = 0;
5211 if (MD->getNumParams() != ExpectedParams) {
5212 // This also checks for default arguments: a copy or move constructor with a
5213 // default argument is classified as a default constructor, and assignment
5214 // operations and destructors can't have default arguments.
5215 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5216 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005217 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005218 } else if (MD->isVariadic()) {
5219 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5220 << CSM << MD->getSourceRange();
5221 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005222 }
5223
Richard Smithb9e90b12012-05-15 04:39:51 +00005224 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005225
Richard Smithb5800092012-06-10 05:43:50 +00005226 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005227 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005228 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005229 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005230 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005231
Richard Smithb9e90b12012-05-15 04:39:51 +00005232 QualType ReturnType = Context.VoidTy;
5233 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5234 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005235 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005236 QualType ExpectedReturnType =
5237 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5238 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5239 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5240 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5241 HadError = true;
5242 }
5243
5244 // A defaulted special member cannot have cv-qualifiers.
5245 if (Type->getTypeQuals()) {
5246 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005247 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005248 HadError = true;
5249 }
5250 }
5251
5252 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005253 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005254 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005255 if (ExpectedParams && ArgType->isReferenceType()) {
5256 // Argument must be reference to possibly-const T.
5257 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005258 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005259
5260 if (ReferentType.isVolatileQualified()) {
5261 Diag(MD->getLocation(),
5262 diag::err_defaulted_special_member_volatile_param) << CSM;
5263 HadError = true;
5264 }
5265
Richard Smithb5800092012-06-10 05:43:50 +00005266 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005267 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5268 Diag(MD->getLocation(),
5269 diag::err_defaulted_special_member_copy_const_param)
5270 << (CSM == CXXCopyAssignment);
5271 // FIXME: Explain why this special member can't be const.
5272 } else {
5273 Diag(MD->getLocation(),
5274 diag::err_defaulted_special_member_move_const_param)
5275 << (CSM == CXXMoveAssignment);
5276 }
5277 HadError = true;
5278 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005279 } else if (ExpectedParams) {
5280 // A copy assignment operator can take its argument by value, but a
5281 // defaulted one cannot.
5282 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005283 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005284 HadError = true;
5285 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005286
Richard Smithcc36f692011-12-22 02:22:31 +00005287 // C++11 [dcl.fct.def.default]p2:
5288 // An explicitly-defaulted function may be declared constexpr only if it
5289 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005290 // Do not apply this rule to members of class templates, since core issue 1358
5291 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005292 // functions which cannot be constexpr (for non-constructors in C++11 and for
5293 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5295 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005296 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005297 : isa<CXXConstructorDecl>(MD)) &&
5298 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005299 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5300 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005301 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005302 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005303 }
Richard Smithbd305122012-12-11 01:14:52 +00005304
Richard Smithcc36f692011-12-22 02:22:31 +00005305 // and may have an explicit exception-specification only if it is compatible
5306 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005307 if (Type->hasExceptionSpec()) {
5308 // Delay the check if this is the first declaration of the special member,
5309 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005310 if (First) {
5311 // If the exception specification needs to be instantiated, do so now,
5312 // before we clobber it with an EST_Unevaluated specification below.
5313 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5314 InstantiateExceptionSpec(MD->getLocStart(), MD);
5315 Type = MD->getType()->getAs<FunctionProtoType>();
5316 }
Richard Smithbd305122012-12-11 01:14:52 +00005317 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005318 } else
Richard Smithbd305122012-12-11 01:14:52 +00005319 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5320 }
Richard Smithcc36f692011-12-22 02:22:31 +00005321
5322 // If a function is explicitly defaulted on its first declaration,
5323 if (First) {
5324 // -- it is implicitly considered to be constexpr if the implicit
5325 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005326 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005327
Richard Smithb9e90b12012-05-15 04:39:51 +00005328 // -- it is implicitly considered to have the same exception-specification
5329 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005330 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005331 EPI.ExceptionSpec.Type = EST_Unevaluated;
5332 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005333 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005334 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005335 ExpectedParams),
5336 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005337 }
5338
Richard Smithb9e90b12012-05-15 04:39:51 +00005339 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005340 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005341 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005342 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005343 // C++11 [dcl.fct.def.default]p4:
5344 // [For a] user-provided explicitly-defaulted function [...] if such a
5345 // function is implicitly defined as deleted, the program is ill-formed.
5346 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005347 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005348 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005349 }
5350 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005351
Richard Smithb9e90b12012-05-15 04:39:51 +00005352 if (HadError)
5353 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005354}
5355
Richard Smithbd305122012-12-11 01:14:52 +00005356/// Check whether the exception specification provided for an
5357/// explicitly-defaulted special member matches the exception specification
5358/// that would have been generated for an implicit special member, per
5359/// C++11 [dcl.fct.def.default]p2.
5360void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5361 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005362 // If the exception specification was explicitly specified but hadn't been
5363 // parsed when the method was defaulted, grab it now.
5364 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5365 SpecifiedType =
5366 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5367
Richard Smithbd305122012-12-11 01:14:52 +00005368 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005369 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5370 /*IsCXXMethod=*/true);
5371 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005372 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5373 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005374 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005375 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005376
5377 // Ensure that it matches.
5378 CheckEquivalentExceptionSpec(
5379 PDiag(diag::err_incorrect_defaulted_exception_spec)
5380 << getSpecialMember(MD), PDiag(),
5381 ImplicitType, SourceLocation(),
5382 SpecifiedType, MD->getLocation());
5383}
5384
Alp Tokerae3a9442013-10-18 05:54:19 +00005385void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005386 decltype(DelayedExceptionSpecChecks) Checks;
5387 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005388
Richard Smith88f45492014-11-22 03:09:05 +00005389 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005390 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5391
5392 // Perform any deferred checking of exception specifications for virtual
5393 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005394 for (auto &Check : Checks)
5395 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005396
5397 // Check that any explicitly-defaulted methods have exception specifications
5398 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005399 for (auto &Spec : Specs)
5400 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005401}
5402
Richard Smithd951a1d2012-02-18 02:02:13 +00005403namespace {
5404struct SpecialMemberDeletionInfo {
5405 Sema &S;
5406 CXXMethodDecl *MD;
5407 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005408 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005409
5410 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005411 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005412 SourceLocation Loc;
5413
5414 bool AllFieldsAreConst;
5415
5416 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005417 Sema::CXXSpecialMember CSM, bool Diagnose)
5418 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005419 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005420 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005421 AllFieldsAreConst(true) {
5422 switch (CSM) {
5423 case Sema::CXXDefaultConstructor:
5424 case Sema::CXXCopyConstructor:
5425 IsConstructor = true;
5426 break;
5427 case Sema::CXXMoveConstructor:
5428 IsConstructor = true;
5429 IsMove = true;
5430 break;
5431 case Sema::CXXCopyAssignment:
5432 IsAssignment = true;
5433 break;
5434 case Sema::CXXMoveAssignment:
5435 IsAssignment = true;
5436 IsMove = true;
5437 break;
5438 case Sema::CXXDestructor:
5439 break;
5440 case Sema::CXXInvalid:
5441 llvm_unreachable("invalid special member kind");
5442 }
5443
5444 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005445 if (const ReferenceType *RT =
5446 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5447 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005448 }
5449 }
5450
5451 bool inUnion() const { return MD->getParent()->isUnion(); }
5452
5453 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005454 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005455 unsigned Quals, bool IsMutable) {
5456 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5457 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005458 }
5459
Richard Smith852265f2012-03-30 20:53:28 +00005460 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005461
Richard Smith852265f2012-03-30 20:53:28 +00005462 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005463 bool shouldDeleteForField(FieldDecl *FD);
5464 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005465
Richard Smithaf136f82012-07-18 03:51:16 +00005466 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5467 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005468 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5469 Sema::SpecialMemberOverloadResult *SMOR,
5470 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005471
5472 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005473};
5474}
5475
John McCalld4274212012-04-09 20:53:23 +00005476/// Is the given special member inaccessible when used on the given
5477/// sub-object.
5478bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5479 CXXMethodDecl *target) {
5480 /// If we're operating on a base class, the object type is the
5481 /// type of this special member.
5482 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005483 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005484 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5485 objectTy = S.Context.getTypeDeclType(MD->getParent());
5486 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5487
5488 // If we're operating on a field, the object type is the type of the field.
5489 } else {
5490 objectTy = S.Context.getTypeDeclType(target->getParent());
5491 }
5492
5493 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5494}
5495
Richard Smith852265f2012-03-30 20:53:28 +00005496/// Check whether we should delete a special member due to the implicit
5497/// definition containing a call to a special member of a subobject.
5498bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5499 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5500 bool IsDtorCallInCtor) {
5501 CXXMethodDecl *Decl = SMOR->getMethod();
5502 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5503
5504 int DiagKind = -1;
5505
5506 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5507 DiagKind = !Decl ? 0 : 1;
5508 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5509 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005510 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005511 DiagKind = 3;
5512 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5513 !Decl->isTrivial()) {
5514 // A member of a union must have a trivial corresponding special member.
5515 // As a weird special case, a destructor call from a union's constructor
5516 // must be accessible and non-deleted, but need not be trivial. Such a
5517 // destructor is never actually called, but is semantically checked as
5518 // if it were.
5519 DiagKind = 4;
5520 }
5521
5522 if (DiagKind == -1)
5523 return false;
5524
5525 if (Diagnose) {
5526 if (Field) {
5527 S.Diag(Field->getLocation(),
5528 diag::note_deleted_special_member_class_subobject)
5529 << CSM << MD->getParent() << /*IsField*/true
5530 << Field << DiagKind << IsDtorCallInCtor;
5531 } else {
5532 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5533 S.Diag(Base->getLocStart(),
5534 diag::note_deleted_special_member_class_subobject)
5535 << CSM << MD->getParent() << /*IsField*/false
5536 << Base->getType() << DiagKind << IsDtorCallInCtor;
5537 }
5538
5539 if (DiagKind == 1)
5540 S.NoteDeletedFunction(Decl);
5541 // FIXME: Explain inaccessibility if DiagKind == 3.
5542 }
5543
5544 return true;
5545}
5546
Richard Smith921bd202012-02-26 09:11:52 +00005547/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005548/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005549bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005550 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005551 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005552 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005553
5554 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005555 // -- any direct or virtual base class, or non-static data member with no
5556 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005557 // either M has no default constructor or overload resolution as applied
5558 // to M's default constructor results in an ambiguity or in a function
5559 // that is deleted or inaccessible
5560 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5561 // -- a direct or virtual base class B that cannot be copied/moved because
5562 // overload resolution, as applied to B's corresponding special member,
5563 // results in an ambiguity or a function that is deleted or inaccessible
5564 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005565 // C++11 [class.dtor]p5:
5566 // -- any direct or virtual base class [...] has a type with a destructor
5567 // that is deleted or inaccessible
5568 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005569 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005570 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5571 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005572 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005573
Richard Smith852265f2012-03-30 20:53:28 +00005574 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5575 // -- any direct or virtual base class or non-static data member has a
5576 // type with a destructor that is deleted or inaccessible
5577 if (IsConstructor) {
5578 Sema::SpecialMemberOverloadResult *SMOR =
5579 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5580 false, false, false, false, false);
5581 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5582 return true;
5583 }
5584
Richard Smith921bd202012-02-26 09:11:52 +00005585 return false;
5586}
5587
5588/// Check whether we should delete a special member function due to the class
5589/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005590bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005591 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005592 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005593}
5594
5595/// Check whether we should delete a special member function due to the class
5596/// having a particular non-static data member.
5597bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5598 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5599 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5600
5601 if (CSM == Sema::CXXDefaultConstructor) {
5602 // For a default constructor, all references must be initialized in-class
5603 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005604 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5605 if (Diagnose)
5606 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5607 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005608 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005609 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005610 // C++11 [class.ctor]p5: any non-variant non-static data member of
5611 // const-qualified type (or array thereof) with no
5612 // brace-or-equal-initializer does not have a user-provided default
5613 // constructor.
5614 if (!inUnion() && FieldType.isConstQualified() &&
5615 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005616 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5617 if (Diagnose)
5618 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005619 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005620 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005621 }
5622
5623 if (inUnion() && !FieldType.isConstQualified())
5624 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005625 } else if (CSM == Sema::CXXCopyConstructor) {
5626 // For a copy constructor, data members must not be of rvalue reference
5627 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005628 if (FieldType->isRValueReferenceType()) {
5629 if (Diagnose)
5630 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5631 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005632 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005633 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005634 } else if (IsAssignment) {
5635 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005636 if (FieldType->isReferenceType()) {
5637 if (Diagnose)
5638 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5639 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005640 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005641 }
5642 if (!FieldRecord && FieldType.isConstQualified()) {
5643 // C++11 [class.copy]p23:
5644 // -- a non-static data member of const non-class type (or array thereof)
5645 if (Diagnose)
5646 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005647 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005648 return true;
5649 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005650 }
5651
5652 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005653 // Some additional restrictions exist on the variant members.
5654 if (!inUnion() && FieldRecord->isUnion() &&
5655 FieldRecord->isAnonymousStructOrUnion()) {
5656 bool AllVariantFieldsAreConst = true;
5657
Richard Smith5704fe82012-03-29 19:00:10 +00005658 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005659 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005660 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005661
5662 if (!UnionFieldType.isConstQualified())
5663 AllVariantFieldsAreConst = false;
5664
Richard Smith921bd202012-02-26 09:11:52 +00005665 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5666 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005667 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005668 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005669 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005670 }
5671
5672 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005673 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005674 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005675 if (Diagnose)
5676 S.Diag(FieldRecord->getLocation(),
5677 diag::note_deleted_default_ctor_all_const)
5678 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005679 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005680 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005681
Richard Smith5704fe82012-03-29 19:00:10 +00005682 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005683 // This is technically non-conformant, but sanity demands it.
5684 return false;
5685 }
5686
Richard Smithaf136f82012-07-18 03:51:16 +00005687 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5688 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005689 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005690 }
5691
5692 return false;
5693}
5694
5695/// C++11 [class.ctor] p5:
5696/// A defaulted default constructor for a class X is defined as deleted if
5697/// X is a union and all of its variant members are of const-qualified type.
5698bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005699 // This is a silly definition, because it gives an empty union a deleted
5700 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005701 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005702 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005703 if (Diagnose)
5704 S.Diag(MD->getParent()->getLocation(),
5705 diag::note_deleted_default_ctor_all_const)
5706 << MD->getParent() << /*not anonymous union*/0;
5707 return true;
5708 }
5709 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005710}
5711
5712/// Determine whether a defaulted special member function should be defined as
5713/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5714/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005715bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5716 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005717 if (MD->isInvalidDecl())
5718 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005719 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005720 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005721 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005722 return false;
5723
Richard Smithd951a1d2012-02-18 02:02:13 +00005724 // C++11 [expr.lambda.prim]p19:
5725 // The closure type associated with a lambda-expression has a
5726 // deleted (8.4.3) default constructor and a deleted copy
5727 // assignment operator.
5728 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005729 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5730 if (Diagnose)
5731 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005732 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005733 }
5734
Richard Smith6f1e2c62012-04-02 20:59:25 +00005735 // For an anonymous struct or union, the copy and assignment special members
5736 // will never be used, so skip the check. For an anonymous union declared at
5737 // namespace scope, the constructor and destructor are used.
5738 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5739 RD->isAnonymousStructOrUnion())
5740 return false;
5741
Richard Smith852265f2012-03-30 20:53:28 +00005742 // C++11 [class.copy]p7, p18:
5743 // If the class definition declares a move constructor or move assignment
5744 // operator, an implicitly declared copy constructor or copy assignment
5745 // operator is defined as deleted.
5746 if (MD->isImplicit() &&
5747 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005748 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005749
5750 // In Microsoft mode, a user-declared move only causes the deletion of the
5751 // corresponding copy operation, not both copy operations.
5752 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005753 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005754 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005755
5756 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005757 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005758 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005759 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005760 break;
5761 }
5762 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005763 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005764 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005765 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005766 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005767
5768 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005769 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005770 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005771 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005772 break;
5773 }
5774 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005775 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005776 }
5777
5778 if (UserDeclaredMove) {
5779 Diag(UserDeclaredMove->getLocation(),
5780 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005781 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005782 << UserDeclaredMove->isMoveAssignmentOperator();
5783 return true;
5784 }
5785 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005786
Richard Smith6f1e2c62012-04-02 20:59:25 +00005787 // Do access control from the special member function
5788 ContextRAII MethodContext(*this, MD);
5789
Richard Smith921bd202012-02-26 09:11:52 +00005790 // C++11 [class.dtor]p5:
5791 // -- for a virtual destructor, lookup of the non-array deallocation function
5792 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005793 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005794 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005795 DeclarationName Name =
5796 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5797 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005798 OperatorDelete, false)) {
5799 if (Diagnose)
5800 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005801 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005802 }
Richard Smith921bd202012-02-26 09:11:52 +00005803 }
5804
Richard Smith852265f2012-03-30 20:53:28 +00005805 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005806
Aaron Ballman574705e2014-03-13 15:41:46 +00005807 for (auto &BI : RD->bases())
5808 if (!BI.isVirtual() &&
5809 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005810 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005811
Richard Smithd1627032013-07-22 18:06:23 +00005812 // Per DR1611, do not consider virtual bases of constructors of abstract
5813 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005814 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005815 for (auto &BI : RD->vbases())
5816 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005817 return true;
5818 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005819
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005820 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005821 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005822 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005823 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005824
Richard Smithd951a1d2012-02-18 02:02:13 +00005825 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005826 return true;
5827
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005828 if (getLangOpts().CUDA) {
5829 // We should delete the special member in CUDA mode if target inference
5830 // failed.
5831 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5832 Diagnose);
5833 }
5834
Alexis Huntea6f0322011-05-11 22:34:38 +00005835 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005836}
5837
Richard Smith92f241f2012-12-08 02:53:02 +00005838/// Perform lookup for a special member of the specified kind, and determine
5839/// whether it is trivial. If the triviality can be determined without the
5840/// lookup, skip it. This is intended for use when determining whether a
5841/// special member of a containing object is trivial, and thus does not ever
5842/// perform overload resolution for default constructors.
5843///
5844/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5845/// member that was most likely to be intended to be trivial, if any.
5846static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5847 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005848 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005849 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005850 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005851
5852 switch (CSM) {
5853 case Sema::CXXInvalid:
5854 llvm_unreachable("not a special member");
5855
5856 case Sema::CXXDefaultConstructor:
5857 // C++11 [class.ctor]p5:
5858 // A default constructor is trivial if:
5859 // - all the [direct subobjects] have trivial default constructors
5860 //
5861 // Note, no overload resolution is performed in this case.
5862 if (RD->hasTrivialDefaultConstructor())
5863 return true;
5864
5865 if (Selected) {
5866 // If there's a default constructor which could have been trivial, dig it
5867 // out. Otherwise, if there's any user-provided default constructor, point
5868 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005869 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005870 if (RD->needsImplicitDefaultConstructor())
5871 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005872 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005873 if (!CI->isDefaultConstructor())
5874 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005875 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005876 if (!DefCtor->isUserProvided())
5877 break;
5878 }
5879
5880 *Selected = DefCtor;
5881 }
5882
5883 return false;
5884
5885 case Sema::CXXDestructor:
5886 // C++11 [class.dtor]p5:
5887 // A destructor is trivial if:
5888 // - all the direct [subobjects] have trivial destructors
5889 if (RD->hasTrivialDestructor())
5890 return true;
5891
5892 if (Selected) {
5893 if (RD->needsImplicitDestructor())
5894 S.DeclareImplicitDestructor(RD);
5895 *Selected = RD->getDestructor();
5896 }
5897
5898 return false;
5899
5900 case Sema::CXXCopyConstructor:
5901 // C++11 [class.copy]p12:
5902 // A copy constructor is trivial if:
5903 // - the constructor selected to copy each direct [subobject] is trivial
5904 if (RD->hasTrivialCopyConstructor()) {
5905 if (Quals == Qualifiers::Const)
5906 // We must either select the trivial copy constructor or reach an
5907 // ambiguity; no need to actually perform overload resolution.
5908 return true;
5909 } else if (!Selected) {
5910 return false;
5911 }
5912 // In C++98, we are not supposed to perform overload resolution here, but we
5913 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5914 // cases like B as having a non-trivial copy constructor:
5915 // struct A { template<typename T> A(T&); };
5916 // struct B { mutable A a; };
5917 goto NeedOverloadResolution;
5918
5919 case Sema::CXXCopyAssignment:
5920 // C++11 [class.copy]p25:
5921 // A copy assignment operator is trivial if:
5922 // - the assignment operator selected to copy each direct [subobject] is
5923 // trivial
5924 if (RD->hasTrivialCopyAssignment()) {
5925 if (Quals == Qualifiers::Const)
5926 return true;
5927 } else if (!Selected) {
5928 return false;
5929 }
5930 // In C++98, we are not supposed to perform overload resolution here, but we
5931 // treat that as a language defect.
5932 goto NeedOverloadResolution;
5933
5934 case Sema::CXXMoveConstructor:
5935 case Sema::CXXMoveAssignment:
5936 NeedOverloadResolution:
5937 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005938 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005939
5940 // The standard doesn't describe how to behave if the lookup is ambiguous.
5941 // We treat it as not making the member non-trivial, just like the standard
5942 // mandates for the default constructor. This should rarely matter, because
5943 // the member will also be deleted.
5944 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5945 return true;
5946
5947 if (!SMOR->getMethod()) {
5948 assert(SMOR->getKind() ==
5949 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5950 return false;
5951 }
5952
5953 // We deliberately don't check if we found a deleted special member. We're
5954 // not supposed to!
5955 if (Selected)
5956 *Selected = SMOR->getMethod();
5957 return SMOR->getMethod()->isTrivial();
5958 }
5959
5960 llvm_unreachable("unknown special method kind");
5961}
5962
Benjamin Kramer3e350262013-02-15 12:30:38 +00005963static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005964 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005965 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005966 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005967
5968 // Look for constructor templates.
5969 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5970 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5971 if (CXXConstructorDecl *CD =
5972 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5973 return CD;
5974 }
5975
Craig Topperc3ec1492014-05-26 06:22:03 +00005976 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005977}
5978
5979/// The kind of subobject we are checking for triviality. The values of this
5980/// enumeration are used in diagnostics.
5981enum TrivialSubobjectKind {
5982 /// The subobject is a base class.
5983 TSK_BaseClass,
5984 /// The subobject is a non-static data member.
5985 TSK_Field,
5986 /// The object is actually the complete object.
5987 TSK_CompleteObject
5988};
5989
5990/// Check whether the special member selected for a given type would be trivial.
5991static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005992 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005993 Sema::CXXSpecialMember CSM,
5994 TrivialSubobjectKind Kind,
5995 bool Diagnose) {
5996 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5997 if (!SubRD)
5998 return true;
5999
6000 CXXMethodDecl *Selected;
6001 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006002 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006003 return true;
6004
6005 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006006 if (ConstRHS)
6007 SubType.addConst();
6008
Richard Smith92f241f2012-12-08 02:53:02 +00006009 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6010 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6011 << Kind << SubType.getUnqualifiedType();
6012 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6013 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6014 } else if (!Selected)
6015 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6016 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6017 else if (Selected->isUserProvided()) {
6018 if (Kind == TSK_CompleteObject)
6019 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6020 << Kind << SubType.getUnqualifiedType() << CSM;
6021 else {
6022 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6023 << Kind << SubType.getUnqualifiedType() << CSM;
6024 S.Diag(Selected->getLocation(), diag::note_declared_at);
6025 }
6026 } else {
6027 if (Kind != TSK_CompleteObject)
6028 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6029 << Kind << SubType.getUnqualifiedType() << CSM;
6030
6031 // Explain why the defaulted or deleted special member isn't trivial.
6032 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6033 }
6034 }
6035
6036 return false;
6037}
6038
6039/// Check whether the members of a class type allow a special member to be
6040/// trivial.
6041static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6042 Sema::CXXSpecialMember CSM,
6043 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006044 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006045 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6046 continue;
6047
6048 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6049
6050 // Pretend anonymous struct or union members are members of this class.
6051 if (FI->isAnonymousStructOrUnion()) {
6052 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6053 CSM, ConstArg, Diagnose))
6054 return false;
6055 continue;
6056 }
6057
6058 // C++11 [class.ctor]p5:
6059 // A default constructor is trivial if [...]
6060 // -- no non-static data member of its class has a
6061 // brace-or-equal-initializer
6062 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6063 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006064 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006065 return false;
6066 }
6067
6068 // Objective C ARC 4.3.5:
6069 // [...] nontrivally ownership-qualified types are [...] not trivially
6070 // default constructible, copy constructible, move constructible, copy
6071 // assignable, move assignable, or destructible [...]
6072 if (S.getLangOpts().ObjCAutoRefCount &&
6073 FieldType.hasNonTrivialObjCLifetime()) {
6074 if (Diagnose)
6075 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6076 << RD << FieldType.getObjCLifetime();
6077 return false;
6078 }
6079
Richard Smith41c35d62013-11-27 03:39:20 +00006080 bool ConstRHS = ConstArg && !FI->isMutable();
6081 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6082 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006083 return false;
6084 }
6085
6086 return true;
6087}
6088
6089/// Diagnose why the specified class does not have a trivial special member of
6090/// the given kind.
6091void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6092 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006093
Richard Smith41c35d62013-11-27 03:39:20 +00006094 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6095 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006096 TSK_CompleteObject, /*Diagnose*/true);
6097}
6098
6099/// Determine whether a defaulted or deleted special member function is trivial,
6100/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6101/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6102bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6103 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006104 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6105
6106 CXXRecordDecl *RD = MD->getParent();
6107
6108 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006109
Richard Smith2002bfe2013-11-04 02:02:27 +00006110 // C++11 [class.copy]p12, p25: [DR1593]
6111 // A [special member] is trivial if [...] its parameter-type-list is
6112 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006113 switch (CSM) {
6114 case CXXDefaultConstructor:
6115 case CXXDestructor:
6116 // Trivial default constructors and destructors cannot have parameters.
6117 break;
6118
6119 case CXXCopyConstructor:
6120 case CXXCopyAssignment: {
6121 // Trivial copy operations always have const, non-volatile parameter types.
6122 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006123 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006124 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6125 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6126 if (Diagnose)
6127 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6128 << Param0->getSourceRange() << Param0->getType()
6129 << Context.getLValueReferenceType(
6130 Context.getRecordType(RD).withConst());
6131 return false;
6132 }
6133 break;
6134 }
6135
6136 case CXXMoveConstructor:
6137 case CXXMoveAssignment: {
6138 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006139 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006140 const RValueReferenceType *RT =
6141 Param0->getType()->getAs<RValueReferenceType>();
6142 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6143 if (Diagnose)
6144 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6145 << Param0->getSourceRange() << Param0->getType()
6146 << Context.getRValueReferenceType(Context.getRecordType(RD));
6147 return false;
6148 }
6149 break;
6150 }
6151
6152 case CXXInvalid:
6153 llvm_unreachable("not a special member");
6154 }
6155
Richard Smith92f241f2012-12-08 02:53:02 +00006156 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6157 if (Diagnose)
6158 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6159 diag::note_nontrivial_default_arg)
6160 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6161 return false;
6162 }
6163 if (MD->isVariadic()) {
6164 if (Diagnose)
6165 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6166 return false;
6167 }
6168
6169 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6170 // A copy/move [constructor or assignment operator] is trivial if
6171 // -- the [member] selected to copy/move each direct base class subobject
6172 // is trivial
6173 //
6174 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6175 // A [default constructor or destructor] is trivial if
6176 // -- all the direct base classes have trivial [default constructors or
6177 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006178 for (const auto &BI : RD->bases())
6179 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006180 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006181 return false;
6182
6183 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6184 // A copy/move [constructor or assignment operator] for a class X is
6185 // trivial if
6186 // -- for each non-static data member of X that is of class type (or array
6187 // thereof), the constructor selected to copy/move that member is
6188 // trivial
6189 //
6190 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6191 // A [default constructor or destructor] is trivial if
6192 // -- for all of the non-static data members of its class that are of class
6193 // type (or array thereof), each such class has a trivial [default
6194 // constructor or destructor]
6195 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6196 return false;
6197
6198 // C++11 [class.dtor]p5:
6199 // A destructor is trivial if [...]
6200 // -- the destructor is not virtual
6201 if (CSM == CXXDestructor && MD->isVirtual()) {
6202 if (Diagnose)
6203 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6204 return false;
6205 }
6206
6207 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6208 // A [special member] for class X is trivial if [...]
6209 // -- class X has no virtual functions and no virtual base classes
6210 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6211 if (!Diagnose)
6212 return false;
6213
6214 if (RD->getNumVBases()) {
6215 // Check for virtual bases. We already know that the corresponding
6216 // member in all bases is trivial, so vbases must all be direct.
6217 CXXBaseSpecifier &BS = *RD->vbases_begin();
6218 assert(BS.isVirtual());
6219 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6220 return false;
6221 }
6222
6223 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006224 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006225 if (MI->isVirtual()) {
6226 SourceLocation MLoc = MI->getLocStart();
6227 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6228 return false;
6229 }
6230 }
6231
6232 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6233 }
6234
6235 // Looks like it's trivial!
6236 return true;
6237}
6238
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006239/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006240namespace {
6241 struct FindHiddenVirtualMethodData {
6242 Sema *S;
6243 CXXMethodDecl *Method;
6244 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006245 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006246 };
6247}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006248
David Blaikie282c92a2012-10-19 00:53:08 +00006249/// \brief Check whether any most overriden method from MD in Methods
6250static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006251 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006252 if (MD->size_overridden_methods() == 0)
6253 return Methods.count(MD->getCanonicalDecl());
6254 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6255 E = MD->end_overridden_methods();
6256 I != E; ++I)
6257 if (CheckMostOverridenMethods(*I, Methods))
6258 return true;
6259 return false;
6260}
6261
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006262/// \brief Member lookup function that determines whether a given C++
6263/// method overloads virtual methods in a base class without overriding any,
6264/// to be used with CXXRecordDecl::lookupInBases().
6265static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6266 CXXBasePath &Path,
6267 void *UserData) {
6268 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6269
6270 FindHiddenVirtualMethodData &Data
6271 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6272
6273 DeclarationName Name = Data.Method->getDeclName();
6274 assert(Name.getNameKind() == DeclarationName::Identifier);
6275
6276 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006277 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006278 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006279 !Path.Decls.empty();
6280 Path.Decls = Path.Decls.slice(1)) {
6281 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006283 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006284 foundSameNameMethod = true;
6285 // Interested only in hidden virtual methods.
6286 if (!MD->isVirtual())
6287 continue;
6288 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006289 // don't warn about the other overloaded methods. Clang deviates from GCC
6290 // by only diagnosing overloads of inherited virtual functions that do not
6291 // override any other virtual functions in the base. GCC's
6292 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6293 // function from a base class. These cases may be better served by a
6294 // warning (not specific to virtual functions) on call sites when the call
6295 // would select a different function from the base class, were it visible.
6296 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006297 if (!Data.S->IsOverload(Data.Method, MD, false))
6298 return true;
6299 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006300 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006301 overloadedMethods.push_back(MD);
6302 }
6303 }
6304
6305 if (foundSameNameMethod)
6306 Data.OverloadedMethods.append(overloadedMethods.begin(),
6307 overloadedMethods.end());
6308 return foundSameNameMethod;
6309}
6310
David Blaikie282c92a2012-10-19 00:53:08 +00006311/// \brief Add the most overriden methods from MD to Methods
6312static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006313 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006314 if (MD->size_overridden_methods() == 0)
6315 Methods.insert(MD->getCanonicalDecl());
6316 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6317 E = MD->end_overridden_methods();
6318 I != E; ++I)
6319 AddMostOverridenMethods(*I, Methods);
6320}
6321
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006322/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006323/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006324void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6325 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006326 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006327 return;
6328
6329 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6330 /*bool RecordPaths=*/false,
6331 /*bool DetectVirtual=*/false);
6332 FindHiddenVirtualMethodData Data;
6333 Data.Method = MD;
6334 Data.S = this;
6335
6336 // Keep the base methods that were overriden or introduced in the subclass
6337 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006338 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006339 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6340 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6341 NamedDecl *ND = *I;
6342 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006343 ND = shad->getTargetDecl();
6344 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6345 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006346 }
6347
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006348 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6349 OverloadedMethods = Data.OverloadedMethods;
6350}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006351
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006352void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6353 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6354 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6355 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6356 PartialDiagnostic PD = PDiag(
6357 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6358 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6359 Diag(overloadedMD->getLocation(), PD);
6360 }
6361}
6362
6363/// \brief Diagnose methods which overload virtual methods in a base class
6364/// without overriding any.
6365void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6366 if (MD->isInvalidDecl())
6367 return;
6368
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006369 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006370 return;
6371
6372 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6373 FindHiddenVirtualMethods(MD, OverloadedMethods);
6374 if (!OverloadedMethods.empty()) {
6375 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6376 << MD << (OverloadedMethods.size() > 1);
6377
6378 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006379 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006380}
6381
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006382void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006383 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006384 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006385 SourceLocation RBrac,
6386 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006387 if (!TagDecl)
6388 return;
Mike Stump11289f42009-09-09 15:08:12 +00006389
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006390 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006391
Rafael Espindola06e1b132012-07-12 04:32:30 +00006392 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6393 if (l->getKind() != AttributeList::AT_Visibility)
6394 continue;
6395 l->setInvalid();
6396 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6397 l->getName();
6398 }
6399
David Blaikie751c5582011-09-22 02:58:26 +00006400 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006401 // strict aliasing violation!
6402 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006403 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006404
Douglas Gregor0be31a22010-07-02 17:43:08 +00006405 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006406 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006407}
6408
Douglas Gregor05379422008-11-03 17:51:48 +00006409/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6410/// special functions, such as the default constructor, copy
6411/// constructor, or destructor, to the given C++ class (C++
6412/// [special]p1). This routine can only be executed just before the
6413/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006414void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006415 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006416 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006417
Richard Smith6b02d462012-12-08 08:32:28 +00006418 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006419 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006420
Richard Smith6b02d462012-12-08 08:32:28 +00006421 // If the properties or semantics of the copy constructor couldn't be
6422 // determined while the class was being declared, force a declaration
6423 // of it now.
6424 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6425 DeclareImplicitCopyConstructor(ClassDecl);
6426 }
6427
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006428 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006429 ++ASTContext::NumImplicitMoveConstructors;
6430
Richard Smith6b02d462012-12-08 08:32:28 +00006431 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6432 DeclareImplicitMoveConstructor(ClassDecl);
6433 }
6434
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006435 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6436 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006437
6438 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006439 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006440 // it shows up in the right place in the vtable and that we diagnose
6441 // problems with the implicit exception specification.
6442 if (ClassDecl->isDynamicClass() ||
6443 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006444 DeclareImplicitCopyAssignment(ClassDecl);
6445 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006446
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006447 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006448 ++ASTContext::NumImplicitMoveAssignmentOperators;
6449
6450 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006451 if (ClassDecl->isDynamicClass() ||
6452 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006453 DeclareImplicitMoveAssignment(ClassDecl);
6454 }
6455
Douglas Gregor7454c562010-07-02 20:37:36 +00006456 if (!ClassDecl->hasUserDeclaredDestructor()) {
6457 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006458
6459 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006460 // have to declare the destructor immediately. This ensures that, e.g., it
6461 // shows up in the right place in the vtable and that we diagnose problems
6462 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006463 if (ClassDecl->isDynamicClass() ||
6464 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006465 DeclareImplicitDestructor(ClassDecl);
6466 }
Douglas Gregor05379422008-11-03 17:51:48 +00006467}
6468
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006469unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006470 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006471 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006472
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006473 // The order of template parameters is not important here. All names
6474 // get added to the same scope.
6475 SmallVector<TemplateParameterList *, 4> ParameterLists;
6476
6477 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6478 D = TD->getTemplatedDecl();
6479
6480 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6481 ParameterLists.push_back(PSD->getTemplateParameters());
6482
6483 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6484 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6485 ParameterLists.push_back(DD->getTemplateParameterList(i));
6486
6487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6488 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6489 ParameterLists.push_back(FTD->getTemplateParameters());
6490 }
6491 }
6492
6493 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6494 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6495 ParameterLists.push_back(TD->getTemplateParameterList(i));
6496
6497 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6498 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6499 ParameterLists.push_back(CTD->getTemplateParameters());
6500 }
6501 }
6502
6503 unsigned Count = 0;
6504 for (TemplateParameterList *Params : ParameterLists) {
6505 if (Params->size() > 0)
6506 // Ignore explicit specializations; they don't contribute to the template
6507 // depth.
6508 ++Count;
6509 for (NamedDecl *Param : *Params) {
6510 if (Param->getDeclName()) {
6511 S->AddDecl(Param);
6512 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006513 }
6514 }
6515 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006516
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006517 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006518}
6519
John McCall48871652010-08-21 09:40:31 +00006520void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006521 if (!RecordD) return;
6522 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006523 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006524 PushDeclContext(S, Record);
6525}
6526
John McCall48871652010-08-21 09:40:31 +00006527void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006528 if (!RecordD) return;
6529 PopDeclContext();
6530}
6531
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006532/// This is used to implement the constant expression evaluation part of the
6533/// attribute enable_if extension. There is nothing in standard C++ which would
6534/// require reentering parameters.
6535void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6536 if (!Param)
6537 return;
6538
6539 S->AddDecl(Param);
6540 if (Param->getDeclName())
6541 IdResolver.AddDecl(Param);
6542}
6543
Douglas Gregor4d87df52008-12-16 21:30:33 +00006544/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6545/// parsing a top-level (non-nested) C++ class, and we are now
6546/// parsing those parts of the given Method declaration that could
6547/// not be parsed earlier (C++ [class.mem]p2), such as default
6548/// arguments. This action should enter the scope of the given
6549/// Method declaration as if we had just parsed the qualified method
6550/// name. However, it should not bring the parameters into scope;
6551/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006552void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006553}
6554
6555/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6556/// C++ method declaration. We're (re-)introducing the given
6557/// function parameter into scope for use in parsing later parts of
6558/// the method declaration. For example, we could see an
6559/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006560void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006561 if (!ParamD)
6562 return;
Mike Stump11289f42009-09-09 15:08:12 +00006563
John McCall48871652010-08-21 09:40:31 +00006564 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006565
6566 // If this parameter has an unparsed default argument, clear it out
6567 // to make way for the parsed default argument.
6568 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006569 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006570
John McCall48871652010-08-21 09:40:31 +00006571 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006572 if (Param->getDeclName())
6573 IdResolver.AddDecl(Param);
6574}
6575
6576/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6577/// processing the delayed method declaration for Method. The method
6578/// declaration is now considered finished. There may be a separate
6579/// ActOnStartOfFunctionDef action later (not necessarily
6580/// immediately!) for this method, if it was also defined inside the
6581/// class body.
John McCall48871652010-08-21 09:40:31 +00006582void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006583 if (!MethodD)
6584 return;
Mike Stump11289f42009-09-09 15:08:12 +00006585
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006586 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006587
John McCall48871652010-08-21 09:40:31 +00006588 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006589
6590 // Now that we have our default arguments, check the constructor
6591 // again. It could produce additional diagnostics or affect whether
6592 // the class has implicitly-declared destructors, among other
6593 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006594 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6595 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006596
6597 // Check the default arguments, which we may have added.
6598 if (!Method->isInvalidDecl())
6599 CheckCXXDefaultArguments(Method);
6600}
6601
Douglas Gregor831c93f2008-11-05 20:51:48 +00006602/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006603/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006604/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006605/// emit diagnostics and set the invalid bit to true. In any case, the type
6606/// will be updated to reflect a well-formed type for the constructor and
6607/// returned.
6608QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006609 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006610 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006611
6612 // C++ [class.ctor]p3:
6613 // A constructor shall not be virtual (10.3) or static (9.4). A
6614 // constructor can be invoked for a const, volatile or const
6615 // volatile object. A constructor shall not be declared const,
6616 // volatile, or const volatile (9.3.2).
6617 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006618 if (!D.isInvalidType())
6619 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6620 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6621 << SourceRange(D.getIdentifierLoc());
6622 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006623 }
John McCall8e7d6562010-08-26 03:08:43 +00006624 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006625 if (!D.isInvalidType())
6626 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6627 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6628 << SourceRange(D.getIdentifierLoc());
6629 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006630 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006631 }
Mike Stump11289f42009-09-09 15:08:12 +00006632
David Majnemer03f705f2014-07-08 18:18:04 +00006633 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6634 diagnoseIgnoredQualifiers(
6635 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6636 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6637 D.getDeclSpec().getRestrictSpecLoc(),
6638 D.getDeclSpec().getAtomicSpecLoc());
6639 D.setInvalidType();
6640 }
6641
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006643 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006644 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006645 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6646 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006647 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006648 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6649 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006650 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006651 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6652 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006653 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
Douglas Gregordb9d6642011-01-26 05:01:58 +00006656 // C++0x [class.ctor]p4:
6657 // A constructor shall not be declared with a ref-qualifier.
6658 if (FTI.hasRefQualifier()) {
6659 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6660 << FTI.RefQualifierIsLValueRef
6661 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6662 D.setInvalidType();
6663 }
6664
Douglas Gregor831c93f2008-11-05 20:51:48 +00006665 // Rebuild the function type "R" without any type qualifiers (in
6666 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006667 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006668 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006669 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006670 return R;
6671
6672 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6673 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006674 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006675
6676 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006677}
6678
Douglas Gregor4d87df52008-12-16 21:30:33 +00006679/// CheckConstructor - Checks a fully-formed constructor for
6680/// well-formedness, issuing any diagnostics required. Returns true if
6681/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006682void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006683 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006684 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6685 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006686 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006687
6688 // C++ [class.copy]p3:
6689 // A declaration of a constructor for a class X is ill-formed if
6690 // its first parameter is of type (optionally cv-qualified) X and
6691 // either there are no other parameters or else all other
6692 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006693 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006694 ((Constructor->getNumParams() == 1) ||
6695 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006696 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6697 Constructor->getTemplateSpecializationKind()
6698 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006699 QualType ParamType = Constructor->getParamDecl(0)->getType();
6700 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6701 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006702 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006703 const char *ConstRef
6704 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6705 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006706 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006707 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006708
6709 // FIXME: Rather that making the constructor invalid, we should endeavor
6710 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006711 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006712 }
6713 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006714}
6715
John McCalldeb646e2010-08-04 01:04:25 +00006716/// CheckDestructor - Checks a fully-formed destructor definition for
6717/// well-formedness, issuing any diagnostics required. Returns true
6718/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006719bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006720 CXXRecordDecl *RD = Destructor->getParent();
6721
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006722 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006723 SourceLocation Loc;
6724
6725 if (!Destructor->isImplicit())
6726 Loc = Destructor->getLocation();
6727 else
6728 Loc = RD->getLocation();
6729
6730 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006731 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006732 DeclarationName Name =
6733 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006734 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006735 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006736 // If there's no class-specific operator delete, look up the global
6737 // non-array delete.
6738 if (!OperatorDelete)
6739 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006740
Eli Friedmanfa0df832012-02-02 03:46:19 +00006741 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006742
6743 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006744 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006745
6746 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006747}
6748
Douglas Gregor831c93f2008-11-05 20:51:48 +00006749/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6750/// the well-formednes of the destructor declarator @p D with type @p
6751/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006752/// emit diagnostics and set the declarator to invalid. Even if this happens,
6753/// will be updated to reflect a well-formed type for the destructor and
6754/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006755QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006756 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006757 // C++ [class.dtor]p1:
6758 // [...] A typedef-name that names a class is a class-name
6759 // (7.1.3); however, a typedef-name that names a class shall not
6760 // be used as the identifier in the declarator for a destructor
6761 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006762 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006763 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006764 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006765 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006766 else if (const TemplateSpecializationType *TST =
6767 DeclaratorType->getAs<TemplateSpecializationType>())
6768 if (TST->isTypeAlias())
6769 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6770 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006771
6772 // C++ [class.dtor]p2:
6773 // A destructor is used to destroy objects of its class type. A
6774 // destructor takes no parameters, and no return type can be
6775 // specified for it (not even void). The address of a destructor
6776 // shall not be taken. A destructor shall not be static. A
6777 // destructor can be invoked for a const, volatile or const
6778 // volatile object. A destructor shall not be declared const,
6779 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006780 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006781 if (!D.isInvalidType())
6782 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6783 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006784 << SourceRange(D.getIdentifierLoc())
6785 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6786
John McCall8e7d6562010-08-26 03:08:43 +00006787 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006788 }
David Majnemer03f705f2014-07-08 18:18:04 +00006789 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006790 // Destructors don't have return types, but the parser will
6791 // happily parse something like:
6792 //
6793 // class X {
6794 // float ~X();
6795 // };
6796 //
6797 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006798 if (D.getDeclSpec().hasTypeSpecifier())
6799 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6800 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6801 << SourceRange(D.getIdentifierLoc());
6802 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6803 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6804 SourceLocation(),
6805 D.getDeclSpec().getConstSpecLoc(),
6806 D.getDeclSpec().getVolatileSpecLoc(),
6807 D.getDeclSpec().getRestrictSpecLoc(),
6808 D.getDeclSpec().getAtomicSpecLoc());
6809 D.setInvalidType();
6810 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006811 }
Mike Stump11289f42009-09-09 15:08:12 +00006812
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006814 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006815 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6817 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006818 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6820 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006821 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6823 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006824 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006825 }
6826
Douglas Gregordb9d6642011-01-26 05:01:58 +00006827 // C++0x [class.dtor]p2:
6828 // A destructor shall not be declared with a ref-qualifier.
6829 if (FTI.hasRefQualifier()) {
6830 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6831 << FTI.RefQualifierIsLValueRef
6832 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6833 D.setInvalidType();
6834 }
6835
Douglas Gregor831c93f2008-11-05 20:51:48 +00006836 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006837 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006838 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6839
6840 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006841 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006842 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006843 }
6844
Mike Stump11289f42009-09-09 15:08:12 +00006845 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006846 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006847 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006848 D.setInvalidType();
6849 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006850
6851 // Rebuild the function type "R" without any type qualifiers or
6852 // parameters (in case any of the errors above fired) and with
6853 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006854 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006855 if (!D.isInvalidType())
6856 return R;
6857
Douglas Gregor95755162010-07-01 05:10:53 +00006858 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006859 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6860 EPI.Variadic = false;
6861 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006862 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006863 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006864}
6865
Richard Smitha865a162014-12-19 02:07:47 +00006866static void extendLeft(SourceRange &R, const SourceRange &Before) {
6867 if (Before.isInvalid())
6868 return;
6869 R.setBegin(Before.getBegin());
6870 if (R.getEnd().isInvalid())
6871 R.setEnd(Before.getEnd());
6872}
6873
6874static void extendRight(SourceRange &R, const SourceRange &After) {
6875 if (After.isInvalid())
6876 return;
6877 if (R.getBegin().isInvalid())
6878 R.setBegin(After.getBegin());
6879 R.setEnd(After.getEnd());
6880}
6881
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006882/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6883/// well-formednes of the conversion function declarator @p D with
6884/// type @p R. If there are any errors in the declarator, this routine
6885/// will emit diagnostics and return true. Otherwise, it will return
6886/// false. Either way, the type @p R will be updated to reflect a
6887/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006888void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006889 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006890 // C++ [class.conv.fct]p1:
6891 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006892 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006893 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006894 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006895 if (!D.isInvalidType())
6896 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006897 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6898 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006899 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006900 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006901 }
John McCall212fa2e2010-04-13 00:04:31 +00006902
Richard Smitha865a162014-12-19 02:07:47 +00006903 TypeSourceInfo *ConvTSI = nullptr;
6904 QualType ConvType =
6905 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006906
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006907 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006908 // Conversion functions don't have return types, but the parser will
6909 // happily parse something like:
6910 //
6911 // class X {
6912 // float operator bool();
6913 // };
6914 //
6915 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006916 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6917 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6918 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006919 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006920 }
6921
John McCall212fa2e2010-04-13 00:04:31 +00006922 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6923
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006924 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006925 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006926 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6927
6928 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006929 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006930 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006931 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006932 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006933 D.setInvalidType();
6934 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006935
John McCall212fa2e2010-04-13 00:04:31 +00006936 // Diagnose "&operator bool()" and other such nonsense. This
6937 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006938 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006939 bool NeedsTypedef = false;
6940 SourceRange Before, After;
6941
6942 // Walk the chunks and extract information on them for our diagnostic.
6943 bool PastFunctionChunk = false;
6944 for (auto &Chunk : D.type_objects()) {
6945 switch (Chunk.Kind) {
6946 case DeclaratorChunk::Function:
6947 if (!PastFunctionChunk) {
6948 if (Chunk.Fun.HasTrailingReturnType) {
6949 TypeSourceInfo *TRT = nullptr;
6950 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6951 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6952 }
6953 PastFunctionChunk = true;
6954 break;
6955 }
6956 // Fall through.
6957 case DeclaratorChunk::Array:
6958 NeedsTypedef = true;
6959 extendRight(After, Chunk.getSourceRange());
6960 break;
6961
6962 case DeclaratorChunk::Pointer:
6963 case DeclaratorChunk::BlockPointer:
6964 case DeclaratorChunk::Reference:
6965 case DeclaratorChunk::MemberPointer:
6966 extendLeft(Before, Chunk.getSourceRange());
6967 break;
6968
6969 case DeclaratorChunk::Paren:
6970 extendLeft(Before, Chunk.Loc);
6971 extendRight(After, Chunk.EndLoc);
6972 break;
6973 }
6974 }
6975
6976 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6977 After.isValid() ? After.getBegin() :
6978 D.getIdentifierLoc();
6979 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6980 DB << Before << After;
6981
6982 if (!NeedsTypedef) {
6983 DB << /*don't need a typedef*/0;
6984
6985 // If we can provide a correct fix-it hint, do so.
6986 if (After.isInvalid() && ConvTSI) {
6987 SourceLocation InsertLoc =
6988 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6989 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6990 << FixItHint::CreateInsertionFromRange(
6991 InsertLoc, CharSourceRange::getTokenRange(Before))
6992 << FixItHint::CreateRemoval(Before);
6993 }
6994 } else if (!Proto->getReturnType()->isDependentType()) {
6995 DB << /*typedef*/1 << Proto->getReturnType();
6996 } else if (getLangOpts().CPlusPlus11) {
6997 DB << /*alias template*/2 << Proto->getReturnType();
6998 } else {
6999 DB << /*might not be fixable*/3;
7000 }
7001
7002 // Recover by incorporating the other type chunks into the result type.
7003 // Note, this does *not* change the name of the function. This is compatible
7004 // with the GCC extension:
7005 // struct S { &operator int(); } s;
7006 // int &r = s.operator int(); // ok in GCC
7007 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007008 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007009 }
7010
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007011 // C++ [class.conv.fct]p4:
7012 // The conversion-type-id shall not represent a function type nor
7013 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007014 if (ConvType->isArrayType()) {
7015 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7016 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007017 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007018 } else if (ConvType->isFunctionType()) {
7019 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7020 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007021 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007022 }
7023
7024 // Rebuild the function type "R" without any parameters (in case any
7025 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007026 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007027 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007028 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007029
Douglas Gregor5fb53972009-01-14 15:45:31 +00007030 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007031 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007032 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007033 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007034 diag::warn_cxx98_compat_explicit_conversion_functions :
7035 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007036 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007037}
7038
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007039/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7040/// the declaration of the given C++ conversion function. This routine
7041/// is responsible for recording the conversion function in the C++
7042/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007043Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007044 assert(Conversion && "Expected to receive a conversion function declaration");
7045
Douglas Gregor4287b372008-12-12 08:25:50 +00007046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007047
7048 // Make sure we aren't redeclaring the conversion function.
7049 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007050
7051 // C++ [class.conv.fct]p1:
7052 // [...] A conversion function is never used to convert a
7053 // (possibly cv-qualified) object to the (possibly cv-qualified)
7054 // same object type (or a reference to it), to a (possibly
7055 // cv-qualified) base class of that type (or a reference to it),
7056 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007057 // FIXME: Suppress this warning if the conversion function ends up being a
7058 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007059 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007060 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007061 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007062 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007063 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7064 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007065 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007066 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007067 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7068 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007069 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007070 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007071 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007072 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007073 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007074 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007075 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007076 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007077 }
7078
Douglas Gregor457104e2010-09-29 04:25:11 +00007079 if (FunctionTemplateDecl *ConversionTemplate
7080 = Conversion->getDescribedFunctionTemplate())
7081 return ConversionTemplate;
7082
John McCall48871652010-08-21 09:40:31 +00007083 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007084}
7085
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007086//===----------------------------------------------------------------------===//
7087// Namespace Handling
7088//===----------------------------------------------------------------------===//
7089
Richard Smith45bb8852012-10-04 22:13:39 +00007090/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7091/// reopened.
7092static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7093 SourceLocation Loc,
7094 IdentifierInfo *II, bool *IsInline,
7095 NamespaceDecl *PrevNS) {
7096 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007097
Richard Smithf501cc32012-10-05 01:46:25 +00007098 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7099 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7100 // inline namespaces, with the intention of bringing names into namespace std.
7101 //
7102 // We support this just well enough to get that case working; this is not
7103 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007104 if (*IsInline && II && II->getName().startswith("__atomic") &&
7105 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007106 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007107 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7108 NS = NS->getPreviousDecl())
7109 NS->setInline(*IsInline);
7110 // Patch up the lookup table for the containing namespace. This isn't really
7111 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007112 for (auto *I : PrevNS->decls())
7113 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007114 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7115 return;
7116 }
7117
7118 if (PrevNS->isInline())
7119 // The user probably just forgot the 'inline', so suggest that it
7120 // be added back.
7121 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7122 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7123 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007124 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007125
7126 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7127 *IsInline = PrevNS->isInline();
7128}
John McCallb1be5232010-08-26 09:15:37 +00007129
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007130/// ActOnStartNamespaceDef - This is called at the start of a namespace
7131/// definition.
John McCall48871652010-08-21 09:40:31 +00007132Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007133 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007134 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007135 SourceLocation IdentLoc,
7136 IdentifierInfo *II,
7137 SourceLocation LBrace,
7138 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007139 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7140 // For anonymous namespace, take the location of the left brace.
7141 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007142 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007143 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007144 bool IsStd = false;
7145 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007146 Scope *DeclRegionScope = NamespcScope->getParent();
7147
Craig Topperc3ec1492014-05-26 06:22:03 +00007148 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007149 if (II) {
7150 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007151 // The identifier in an original-namespace-definition shall not
7152 // have been previously defined in the declarative region in
7153 // which the original-namespace-definition appears. The
7154 // identifier in an original-namespace-definition is the name of
7155 // the namespace. Subsequently in that declarative region, it is
7156 // treated as an original-namespace-name.
7157 //
7158 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007159 // look through using directives, just look for any ordinary names.
7160
7161 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007162 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7163 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007164 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007165 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7166 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7167 ++I) {
7168 if ((*I)->getIdentifierNamespace() & IDNS) {
7169 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007170 break;
7171 }
7172 }
7173
Douglas Gregore57e7522012-01-07 09:11:48 +00007174 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7175
7176 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007177 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007178 if (IsInline != PrevNS->isInline())
7179 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7180 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007181 } else if (PrevDecl) {
7182 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007183 Diag(Loc, diag::err_redefinition_different_kind)
7184 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007185 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007186 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007187 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007188 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007189 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007190 // This is the first "real" definition of the namespace "std", so update
7191 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007192 PrevNS = getStdNamespace();
7193 IsStd = true;
7194 AddToKnown = !IsInline;
7195 } else {
7196 // We've seen this namespace for the first time.
7197 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007198 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007199 } else {
John McCall4fa53422009-10-01 00:25:31 +00007200 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007201
7202 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007203 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007204 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007205 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007206 } else {
7207 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007208 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007209 }
7210
Richard Smith45bb8852012-10-04 22:13:39 +00007211 if (PrevNS && IsInline != PrevNS->isInline())
7212 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7213 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007214 }
7215
7216 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7217 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007218 if (IsInvalid)
7219 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007220
7221 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007222
Douglas Gregore57e7522012-01-07 09:11:48 +00007223 // FIXME: Should we be merging attributes?
7224 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007225 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007226
7227 if (IsStd)
7228 StdNamespace = Namespc;
7229 if (AddToKnown)
7230 KnownNamespaces[Namespc] = false;
7231
7232 if (II) {
7233 PushOnScopeChains(Namespc, DeclRegionScope);
7234 } else {
7235 // Link the anonymous namespace into its parent.
7236 DeclContext *Parent = CurContext->getRedeclContext();
7237 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7238 TU->setAnonymousNamespace(Namespc);
7239 } else {
7240 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007241 }
John McCall4fa53422009-10-01 00:25:31 +00007242
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007243 CurContext->addDecl(Namespc);
7244
John McCall4fa53422009-10-01 00:25:31 +00007245 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7246 // behaves as if it were replaced by
7247 // namespace unique { /* empty body */ }
7248 // using namespace unique;
7249 // namespace unique { namespace-body }
7250 // where all occurrences of 'unique' in a translation unit are
7251 // replaced by the same identifier and this identifier differs
7252 // from all other identifiers in the entire program.
7253
7254 // We just create the namespace with an empty name and then add an
7255 // implicit using declaration, just like the standard suggests.
7256 //
7257 // CodeGen enforces the "universally unique" aspect by giving all
7258 // declarations semantically contained within an anonymous
7259 // namespace internal linkage.
7260
Douglas Gregore57e7522012-01-07 09:11:48 +00007261 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007262 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007263 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007264 /* 'using' */ LBrace,
7265 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007266 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007267 /* identifier */ SourceLocation(),
7268 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007269 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007270 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007271 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007272 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007273 }
7274
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007275 ActOnDocumentableDecl(Namespc);
7276
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007277 // Although we could have an invalid decl (i.e. the namespace name is a
7278 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007279 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7280 // for the namespace has the declarations that showed up in that particular
7281 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007282 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007283 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007284}
7285
Sebastian Redla6602e92009-11-23 15:34:23 +00007286/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7287/// is a namespace alias, returns the namespace it points to.
7288static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7289 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7290 return AD->getNamespace();
7291 return dyn_cast_or_null<NamespaceDecl>(D);
7292}
7293
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007294/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7295/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007296void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007297 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7298 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007299 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007300 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007301 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007302 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007303}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007304
John McCall28a0cf72010-08-25 07:42:41 +00007305CXXRecordDecl *Sema::getStdBadAlloc() const {
7306 return cast_or_null<CXXRecordDecl>(
7307 StdBadAlloc.get(Context.getExternalSource()));
7308}
7309
7310NamespaceDecl *Sema::getStdNamespace() const {
7311 return cast_or_null<NamespaceDecl>(
7312 StdNamespace.get(Context.getExternalSource()));
7313}
7314
Douglas Gregorcdf87022010-06-29 17:53:46 +00007315/// \brief Retrieve the special "std" namespace, which may require us to
7316/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007317NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007318 if (!StdNamespace) {
7319 // The "std" namespace has not yet been defined, so build one implicitly.
7320 StdNamespace = NamespaceDecl::Create(Context,
7321 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007322 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007323 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007324 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007325 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007326 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007327 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007328
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007329 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007330}
7331
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007332bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007333 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007334 "Looking for std::initializer_list outside of C++.");
7335
7336 // We're looking for implicit instantiations of
7337 // template <typename E> class std::initializer_list.
7338
7339 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7340 return false;
7341
Craig Topperc3ec1492014-05-26 06:22:03 +00007342 ClassTemplateDecl *Template = nullptr;
7343 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007344
Sebastian Redl43144e72012-01-17 22:49:58 +00007345 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007346
Sebastian Redl43144e72012-01-17 22:49:58 +00007347 ClassTemplateSpecializationDecl *Specialization =
7348 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7349 if (!Specialization)
7350 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007351
Sebastian Redl43144e72012-01-17 22:49:58 +00007352 Template = Specialization->getSpecializedTemplate();
7353 Arguments = Specialization->getTemplateArgs().data();
7354 } else if (const TemplateSpecializationType *TST =
7355 Ty->getAs<TemplateSpecializationType>()) {
7356 Template = dyn_cast_or_null<ClassTemplateDecl>(
7357 TST->getTemplateName().getAsTemplateDecl());
7358 Arguments = TST->getArgs();
7359 }
7360 if (!Template)
7361 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007362
7363 if (!StdInitializerList) {
7364 // Haven't recognized std::initializer_list yet, maybe this is it.
7365 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7366 if (TemplateClass->getIdentifier() !=
7367 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007368 !getStdNamespace()->InEnclosingNamespaceSetOf(
7369 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007370 return false;
7371 // This is a template called std::initializer_list, but is it the right
7372 // template?
7373 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007374 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007375 return false;
7376 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7377 return false;
7378
7379 // It's the right template.
7380 StdInitializerList = Template;
7381 }
7382
7383 if (Template != StdInitializerList)
7384 return false;
7385
7386 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007387 if (Element)
7388 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007389 return true;
7390}
7391
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007392static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7393 NamespaceDecl *Std = S.getStdNamespace();
7394 if (!Std) {
7395 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007396 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007397 }
7398
7399 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7400 Loc, Sema::LookupOrdinaryName);
7401 if (!S.LookupQualifiedName(Result, Std)) {
7402 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007403 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007404 }
7405 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7406 if (!Template) {
7407 Result.suppressDiagnostics();
7408 // We found something weird. Complain about the first thing we found.
7409 NamedDecl *Found = *Result.begin();
7410 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007411 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007412 }
7413
7414 // We found some template called std::initializer_list. Now verify that it's
7415 // correct.
7416 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007417 if (Params->getMinRequiredArguments() != 1 ||
7418 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007419 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007420 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007421 }
7422
7423 return Template;
7424}
7425
7426QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7427 if (!StdInitializerList) {
7428 StdInitializerList = LookupStdInitializerList(*this, Loc);
7429 if (!StdInitializerList)
7430 return QualType();
7431 }
7432
7433 TemplateArgumentListInfo Args(Loc, Loc);
7434 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7435 Context.getTrivialTypeSourceInfo(Element,
7436 Loc)));
7437 return Context.getCanonicalType(
7438 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7439}
7440
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007441bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7442 // C++ [dcl.init.list]p2:
7443 // A constructor is an initializer-list constructor if its first parameter
7444 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7445 // std::initializer_list<E> for some type E, and either there are no other
7446 // parameters or else all other parameters have default arguments.
7447 if (Ctor->getNumParams() < 1 ||
7448 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7449 return false;
7450
7451 QualType ArgType = Ctor->getParamDecl(0)->getType();
7452 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7453 ArgType = RT->getPointeeType().getUnqualifiedType();
7454
Craig Topperc3ec1492014-05-26 06:22:03 +00007455 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007456}
7457
Douglas Gregora172e082011-03-26 22:25:30 +00007458/// \brief Determine whether a using statement is in a context where it will be
7459/// apply in all contexts.
7460static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7461 switch (CurContext->getDeclKind()) {
7462 case Decl::TranslationUnit:
7463 return true;
7464 case Decl::LinkageSpec:
7465 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7466 default:
7467 return false;
7468 }
7469}
7470
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007471namespace {
7472
7473// Callback to only accept typo corrections that are namespaces.
7474class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007475public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007476 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007477 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007478 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007479 return false;
7480 }
7481};
7482
7483}
7484
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007485static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7486 CXXScopeSpec &SS,
7487 SourceLocation IdentLoc,
7488 IdentifierInfo *Ident) {
7489 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007490 if (TypoCorrection Corrected =
7491 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7492 llvm::make_unique<NamespaceValidatorCCC>(),
7493 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007494 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007495 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7496 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007497 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007498 S.diagnoseTypo(Corrected,
7499 S.PDiag(diag::err_using_directive_member_suggest)
7500 << Ident << DC << DroppedSpecifier << SS.getRange(),
7501 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007502 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007503 S.diagnoseTypo(Corrected,
7504 S.PDiag(diag::err_using_directive_suggest) << Ident,
7505 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007506 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007507 R.addDecl(Corrected.getCorrectionDecl());
7508 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007509 }
7510 return false;
7511}
7512
John McCall48871652010-08-21 09:40:31 +00007513Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007514 SourceLocation UsingLoc,
7515 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007516 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007517 SourceLocation IdentLoc,
7518 IdentifierInfo *NamespcName,
7519 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007520 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7521 assert(NamespcName && "Invalid NamespcName.");
7522 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007523
7524 // This can only happen along a recovery path.
7525 while (S->getFlags() & Scope::TemplateParamScope)
7526 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007527 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007528
Craig Topperc3ec1492014-05-26 06:22:03 +00007529 UsingDirectiveDecl *UDir = nullptr;
7530 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007531 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007532 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007533
Douglas Gregor34074322009-01-14 22:20:51 +00007534 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007535 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7536 LookupParsedName(R, S, &SS);
7537 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007538 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007539
Douglas Gregorcdf87022010-06-29 17:53:46 +00007540 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007541 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007542 // Allow "using namespace std;" or "using namespace ::std;" even if
7543 // "std" hasn't been defined yet, for GCC compatibility.
7544 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7545 NamespcName->isStr("std")) {
7546 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007547 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007548 R.resolveKind();
7549 }
7550 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007551 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007552 }
7553
John McCall9f3059a2009-10-09 21:13:30 +00007554 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007555 NamedDecl *Named = R.getFoundDecl();
7556 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7557 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007558
Nico Riecke50e59a2014-11-24 17:29:52 +00007559 // The use of a nested name specifier may trigger deprecation warnings.
7560 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007561
Douglas Gregor889ceb72009-02-03 19:21:40 +00007562 // C++ [namespace.udir]p1:
7563 // A using-directive specifies that the names in the nominated
7564 // namespace can be used in the scope in which the
7565 // using-directive appears after the using-directive. During
7566 // unqualified name lookup (3.4.1), the names appear as if they
7567 // were declared in the nearest enclosing namespace which
7568 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007569 // namespace. [Note: in this context, "contains" means "contains
7570 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007571
7572 // Find enclosing context containing both using-directive and
7573 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007574 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007575 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7576 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7577 CommonAncestor = CommonAncestor->getParent();
7578
Sebastian Redla6602e92009-11-23 15:34:23 +00007579 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007580 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007581 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007582
Douglas Gregora172e082011-03-26 22:25:30 +00007583 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007584 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007585 Diag(IdentLoc, diag::warn_using_directive_in_header);
7586 }
7587
Douglas Gregor889ceb72009-02-03 19:21:40 +00007588 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007589 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007590 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007591 }
7592
Richard Smith54ecd982013-02-20 19:22:51 +00007593 if (UDir)
7594 ProcessDeclAttributeList(S, UDir, AttrList);
7595
John McCall48871652010-08-21 09:40:31 +00007596 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007597}
7598
7599void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007600 // If the scope has an associated entity and the using directive is at
7601 // namespace or translation unit scope, add the UsingDirectiveDecl into
7602 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007603 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007604 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007605 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007606 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007607 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007608 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007609 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007610}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007611
Douglas Gregorfec52632009-06-20 00:51:54 +00007612
John McCall48871652010-08-21 09:40:31 +00007613Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007614 AccessSpecifier AS,
7615 bool HasUsingKeyword,
7616 SourceLocation UsingLoc,
7617 CXXScopeSpec &SS,
7618 UnqualifiedId &Name,
7619 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007620 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007621 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007622 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007623
Douglas Gregor220f4272009-11-04 16:30:06 +00007624 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007625 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007626 case UnqualifiedId::IK_Identifier:
7627 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007628 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007629 case UnqualifiedId::IK_ConversionFunctionId:
7630 break;
7631
7632 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007633 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007634 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007635 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007636 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007637 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007638 diag::err_using_decl_constructor)
7639 << SS.getRange();
7640
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007641 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007642
Craig Topperc3ec1492014-05-26 06:22:03 +00007643 return nullptr;
7644
Douglas Gregor220f4272009-11-04 16:30:06 +00007645 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007646 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007647 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007648 return nullptr;
7649
Douglas Gregor220f4272009-11-04 16:30:06 +00007650 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007651 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007652 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007653 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007654 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007655
7656 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7657 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007658 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007659 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007660
Richard Smithc2bc61b2013-03-18 21:12:30 +00007661 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007662 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007663 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007664 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7665 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007666 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007667 }
7668
Douglas Gregorc4356532010-12-16 00:46:58 +00007669 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7670 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007671 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007672
John McCall3f746822009-11-17 05:59:44 +00007673 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007674 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007675 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007676 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007677 if (UD)
7678 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007679
John McCall48871652010-08-21 09:40:31 +00007680 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007681}
7682
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007683/// \brief Determine whether a using declaration considers the given
7684/// declarations as "equivalent", e.g., if they are redeclarations of
7685/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007686static bool
7687IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7688 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007689 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007690
Richard Smithdda56e42011-04-15 14:24:37 +00007691 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007692 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007693 return Context.hasSameType(TD1->getUnderlyingType(),
7694 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007695
7696 return false;
7697}
7698
7699
John McCall84d87672009-12-10 09:41:52 +00007700/// Determines whether to create a using shadow decl for a particular
7701/// decl, given the set of decls existing prior to this using lookup.
7702bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007703 const LookupResult &Previous,
7704 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007705 // Diagnose finding a decl which is not from a base class of the
7706 // current class. We do this now because there are cases where this
7707 // function will silently decide not to build a shadow decl, which
7708 // will pre-empt further diagnostics.
7709 //
7710 // We don't need to do this in C++0x because we do the check once on
7711 // the qualifier.
7712 //
7713 // FIXME: diagnose the following if we care enough:
7714 // struct A { int foo; };
7715 // struct B : A { using A::foo; };
7716 // template <class T> struct C : A {};
7717 // template <class T> struct D : C<T> { using B::foo; } // <---
7718 // This is invalid (during instantiation) in C++03 because B::foo
7719 // resolves to the using decl in B, which is not a base class of D<T>.
7720 // We can't diagnose it immediately because C<T> is an unknown
7721 // specialization. The UsingShadowDecl in D<T> then points directly
7722 // to A::foo, which will look well-formed when we instantiate.
7723 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007724 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007725 DeclContext *OrigDC = Orig->getDeclContext();
7726
7727 // Handle enums and anonymous structs.
7728 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7729 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7730 while (OrigRec->isAnonymousStructOrUnion())
7731 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7732
7733 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7734 if (OrigDC == CurContext) {
7735 Diag(Using->getLocation(),
7736 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007737 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007738 Diag(Orig->getLocation(), diag::note_using_decl_target);
7739 return true;
7740 }
7741
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007742 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007743 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007744 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007745 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007746 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007747 Diag(Orig->getLocation(), diag::note_using_decl_target);
7748 return true;
7749 }
7750 }
7751
7752 if (Previous.empty()) return false;
7753
7754 NamedDecl *Target = Orig;
7755 if (isa<UsingShadowDecl>(Target))
7756 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7757
John McCalla17e83e2009-12-11 02:33:26 +00007758 // If the target happens to be one of the previous declarations, we
7759 // don't have a conflict.
7760 //
7761 // FIXME: but we might be increasing its access, in which case we
7762 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007763 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007764 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007765 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7766 I != E; ++I) {
7767 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007768 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7769 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7770 PrevShadow = Shadow;
7771 FoundEquivalentDecl = true;
7772 }
John McCalla17e83e2009-12-11 02:33:26 +00007773
7774 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7775 }
7776
Richard Smithfd8634a2013-10-23 02:17:46 +00007777 if (FoundEquivalentDecl)
7778 return false;
7779
Alp Tokera2794f92014-01-22 07:29:52 +00007780 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007781 NamedDecl *OldDecl = nullptr;
7782 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7783 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007784 case Ovl_Overload:
7785 return false;
7786
7787 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007788 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007789 break;
Richard Smith18819302014-02-06 01:31:33 +00007790
John McCall84d87672009-12-10 09:41:52 +00007791 // We found a decl with the exact signature.
7792 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007793 // If we're in a record, we want to hide the target, so we
7794 // return true (without a diagnostic) to tell the caller not to
7795 // build a shadow decl.
7796 if (CurContext->isRecord())
7797 return true;
7798
7799 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007800 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007801 break;
7802 }
7803
7804 Diag(Target->getLocation(), diag::note_using_decl_target);
7805 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7806 return true;
7807 }
7808
7809 // Target is not a function.
7810
John McCall84d87672009-12-10 09:41:52 +00007811 if (isa<TagDecl>(Target)) {
7812 // No conflict between a tag and a non-tag.
7813 if (!Tag) return false;
7814
John McCalle29c5cd2009-12-10 19:51:03 +00007815 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007816 Diag(Target->getLocation(), diag::note_using_decl_target);
7817 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7818 return true;
7819 }
7820
7821 // No conflict between a tag and a non-tag.
7822 if (!NonTag) return false;
7823
John McCalle29c5cd2009-12-10 19:51:03 +00007824 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007825 Diag(Target->getLocation(), diag::note_using_decl_target);
7826 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7827 return true;
7828}
7829
John McCall3f746822009-11-17 05:59:44 +00007830/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007831UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007832 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007833 NamedDecl *Orig,
7834 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007835
7836 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007837 NamedDecl *Target = Orig;
7838 if (isa<UsingShadowDecl>(Target)) {
7839 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7840 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007841 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007842
John McCall3f746822009-11-17 05:59:44 +00007843 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007844 = UsingShadowDecl::Create(Context, CurContext,
7845 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007846 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007847
Douglas Gregor457104e2010-09-29 04:25:11 +00007848 Shadow->setAccess(UD->getAccess());
7849 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7850 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007851
7852 Shadow->setPreviousDecl(PrevDecl);
7853
John McCall3f746822009-11-17 05:59:44 +00007854 if (S)
John McCall3969e302009-12-08 07:46:18 +00007855 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007856 else
John McCall3969e302009-12-08 07:46:18 +00007857 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007858
John McCall3969e302009-12-08 07:46:18 +00007859
John McCall84d87672009-12-10 09:41:52 +00007860 return Shadow;
7861}
John McCall3969e302009-12-08 07:46:18 +00007862
John McCall84d87672009-12-10 09:41:52 +00007863/// Hides a using shadow declaration. This is required by the current
7864/// using-decl implementation when a resolvable using declaration in a
7865/// class is followed by a declaration which would hide or override
7866/// one or more of the using decl's targets; for example:
7867///
7868/// struct Base { void foo(int); };
7869/// struct Derived : Base {
7870/// using Base::foo;
7871/// void foo(int);
7872/// };
7873///
7874/// The governing language is C++03 [namespace.udecl]p12:
7875///
7876/// When a using-declaration brings names from a base class into a
7877/// derived class scope, member functions in the derived class
7878/// override and/or hide member functions with the same name and
7879/// parameter types in a base class (rather than conflicting).
7880///
7881/// There are two ways to implement this:
7882/// (1) optimistically create shadow decls when they're not hidden
7883/// by existing declarations, or
7884/// (2) don't create any shadow decls (or at least don't make them
7885/// visible) until we've fully parsed/instantiated the class.
7886/// The problem with (1) is that we might have to retroactively remove
7887/// a shadow decl, which requires several O(n) operations because the
7888/// decl structures are (very reasonably) not designed for removal.
7889/// (2) avoids this but is very fiddly and phase-dependent.
7890void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007891 if (Shadow->getDeclName().getNameKind() ==
7892 DeclarationName::CXXConversionFunctionName)
7893 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7894
John McCall84d87672009-12-10 09:41:52 +00007895 // Remove it from the DeclContext...
7896 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007897
John McCall84d87672009-12-10 09:41:52 +00007898 // ...and the scope, if applicable...
7899 if (S) {
John McCall48871652010-08-21 09:40:31 +00007900 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007901 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007902 }
7903
John McCall84d87672009-12-10 09:41:52 +00007904 // ...and the using decl.
7905 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7906
7907 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007908 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007909}
7910
Richard Smith09d5b3a2014-05-01 00:35:04 +00007911/// Find the base specifier for a base class with the given type.
7912static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7913 QualType DesiredBase,
7914 bool &AnyDependentBases) {
7915 // Check whether the named type is a direct base class.
7916 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7917 for (auto &Base : Derived->bases()) {
7918 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7919 if (CanonicalDesiredBase == BaseType)
7920 return &Base;
7921 if (BaseType->isDependentType())
7922 AnyDependentBases = true;
7923 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007924 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007925}
7926
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007927namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007928class UsingValidatorCCC : public CorrectionCandidateCallback {
7929public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007930 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007931 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007932 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007933 IsInstantiation(IsInstantiation), OldNNS(NNS),
7934 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007935
Craig Toppera798a9d2014-03-02 09:32:10 +00007936 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007937 NamedDecl *ND = Candidate.getCorrectionDecl();
7938
7939 // Keywords are not valid here.
7940 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007941 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007942
7943 // Completely unqualified names are invalid for a 'using' declaration.
7944 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7945 return false;
7946
Richard Smith09d5b3a2014-05-01 00:35:04 +00007947 if (RequireMemberOf) {
7948 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7949 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7950 // No-one ever wants a using-declaration to name an injected-class-name
7951 // of a base class, unless they're declaring an inheriting constructor.
7952 ASTContext &Ctx = ND->getASTContext();
7953 if (!Ctx.getLangOpts().CPlusPlus11)
7954 return false;
7955 QualType FoundType = Ctx.getRecordType(FoundRecord);
7956
7957 // Check that the injected-class-name is named as a member of its own
7958 // type; we don't want to suggest 'using Derived::Base;', since that
7959 // means something else.
7960 NestedNameSpecifier *Specifier =
7961 Candidate.WillReplaceSpecifier()
7962 ? Candidate.getCorrectionSpecifier()
7963 : OldNNS;
7964 if (!Specifier->getAsType() ||
7965 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7966 return false;
7967
7968 // Check that this inheriting constructor declaration actually names a
7969 // direct base class of the current class.
7970 bool AnyDependentBases = false;
7971 if (!findDirectBaseWithType(RequireMemberOf,
7972 Ctx.getRecordType(FoundRecord),
7973 AnyDependentBases) &&
7974 !AnyDependentBases)
7975 return false;
7976 } else {
7977 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7978 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7979 return false;
7980
7981 // FIXME: Check that the base class member is accessible?
7982 }
7983 }
7984
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007985 if (isa<TypeDecl>(ND))
7986 return HasTypenameKeyword || !IsInstantiation;
7987
7988 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007989 }
7990
7991private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007992 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007993 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007994 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007995 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007996};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007997} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007998
John McCalle61f2ba2009-11-18 02:36:19 +00007999/// Builds a using declaration.
8000///
8001/// \param IsInstantiation - Whether this call arises from an
8002/// instantiation of an unresolved using declaration. We treat
8003/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008004NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8005 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008006 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008007 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008008 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008009 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008010 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008011 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008012 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008013 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008014 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008015
Anders Carlssonf038fc22009-08-28 05:49:21 +00008016 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008017
Anders Carlsson59140b32009-08-28 03:16:11 +00008018 if (SS.isEmpty()) {
8019 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008020 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008021 }
Mike Stump11289f42009-09-09 15:08:12 +00008022
John McCall84d87672009-12-10 09:41:52 +00008023 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008024 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008025 ForRedeclaration);
8026 Previous.setHideTags(false);
8027 if (S) {
8028 LookupName(Previous, S);
8029
8030 // It is really dumb that we have to do this.
8031 LookupResult::Filter F = Previous.makeFilter();
8032 while (F.hasNext()) {
8033 NamedDecl *D = F.next();
8034 if (!isDeclInScope(D, CurContext, S))
8035 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008036 // If we found a local extern declaration that's not ordinarily visible,
8037 // and this declaration is being added to a non-block scope, ignore it.
8038 // We're only checking for scope conflicts here, not also for violations
8039 // of the linkage rules.
8040 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8041 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8042 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008043 }
8044 F.done();
8045 } else {
8046 assert(IsInstantiation && "no scope in non-instantiation");
8047 assert(CurContext->isRecord() && "scope not record in instantiation");
8048 LookupQualifiedName(Previous, CurContext);
8049 }
8050
John McCall84d87672009-12-10 09:41:52 +00008051 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008052 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8053 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008054 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008055
8056 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008057 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008058 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008059
John McCall84c16cf2009-11-12 03:15:40 +00008060 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008061 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008062 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008063 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008064 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008065 // FIXME: not all declaration name kinds are legal here
8066 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8067 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008068 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008069 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008070 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008071 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8072 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008073 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008074 D->setAccess(AS);
8075 CurContext->addDecl(D);
8076 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008077 }
John McCallb96ec562009-12-04 22:46:56 +00008078
Richard Smith09d5b3a2014-05-01 00:35:04 +00008079 auto Build = [&](bool Invalid) {
8080 UsingDecl *UD =
8081 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8082 HasTypenameKeyword);
8083 UD->setAccess(AS);
8084 CurContext->addDecl(UD);
8085 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008086 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008087 };
8088 auto BuildInvalid = [&]{ return Build(true); };
8089 auto BuildValid = [&]{ return Build(false); };
8090
8091 if (RequireCompleteDeclContext(SS, LookupContext))
8092 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008093
Richard Smith23d55872012-04-02 01:30:27 +00008094 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00008095 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00008096 UsingDecl *UD = BuildValid();
8097 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00008098 return UD;
8099 }
8100
8101 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00008102
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008103 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008104
John McCall3969e302009-12-08 07:46:18 +00008105 // Unlike most lookups, we don't always want to hide tag
8106 // declarations: tag names are visible through the using declaration
8107 // even if hidden by ordinary names, *except* in a dependent context
8108 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008109 if (!IsInstantiation)
8110 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008111
John McCall5dadb652012-04-07 03:04:20 +00008112 // For the purposes of this lookup, we have a base object type
8113 // equal to that of the current context.
8114 if (CurContext->isRecord()) {
8115 R.setBaseObjectType(
8116 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8117 }
8118
John McCall27b18f82009-11-17 02:14:36 +00008119 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008120
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008121 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00008122 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008123 if (TypoCorrection Corrected = CorrectTypo(
8124 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8125 llvm::make_unique<UsingValidatorCCC>(
8126 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8127 dyn_cast<CXXRecordDecl>(CurContext)),
8128 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008129 // We reject any correction for which ND would be NULL.
8130 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008131
Richard Smithf9b15102013-08-17 00:46:16 +00008132 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008133 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008134 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8135 << NameInfo.getName() << LookupContext << 0
8136 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008137
8138 // If we corrected to an inheriting constructor, handle it as one.
8139 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8140 if (RD && RD->isInjectedClassName()) {
8141 // Fix up the information we'll use to build the using declaration.
8142 if (Corrected.WillReplaceSpecifier()) {
8143 NestedNameSpecifierLocBuilder Builder;
8144 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8145 QualifierLoc.getSourceRange());
8146 QualifierLoc = Builder.getWithLocInContext(Context);
8147 }
8148
8149 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8150 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008151 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008152
8153 // Build it and process it as an inheriting constructor.
8154 UsingDecl *UD = BuildValid();
8155 CheckInheritingConstructorUsingDecl(UD);
8156 return UD;
8157 }
8158
8159 // FIXME: Pick up all the declarations if we found an overloaded function.
8160 R.setLookupName(Corrected.getCorrection());
8161 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008162 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008163 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008164 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008165 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008166 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008167 }
8168
Richard Smith09d5b3a2014-05-01 00:35:04 +00008169 if (R.isAmbiguous())
8170 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008171
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008172 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008173 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008174 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008175 Diag(IdentLoc, diag::err_using_typename_non_type);
8176 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8177 Diag((*I)->getUnderlyingDecl()->getLocation(),
8178 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008179 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008180 }
8181 } else {
8182 // If we asked for a non-typename and we got a type, error out,
8183 // but only if this is an instantiation of an unresolved using
8184 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008185 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008186 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8187 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008188 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008189 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008190 }
8191
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008192 // C++0x N2914 [namespace.udecl]p6:
8193 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008194 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008195 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8196 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008197 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008198 }
Mike Stump11289f42009-09-09 15:08:12 +00008199
Richard Smith09d5b3a2014-05-01 00:35:04 +00008200 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008201 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008202 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008203 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8204 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008205 }
John McCall3f746822009-11-17 05:59:44 +00008206
8207 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008208}
8209
Sebastian Redl08905022011-02-05 19:23:19 +00008210/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008211bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008212 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008213
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008214 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008215 assert(SourceType &&
8216 "Using decl naming constructor doesn't have type in scope spec.");
8217 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8218
8219 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008220 bool AnyDependentBases = false;
8221 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8222 AnyDependentBases);
8223 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008224 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008225 diag::err_using_decl_constructor_not_in_direct_base)
8226 << UD->getNameInfo().getSourceRange()
8227 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008228 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008229 return true;
8230 }
8231
Richard Smith09d5b3a2014-05-01 00:35:04 +00008232 if (Base)
8233 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008234
8235 return false;
8236}
8237
John McCall84d87672009-12-10 09:41:52 +00008238/// Checks that the given using declaration is not an invalid
8239/// redeclaration. Note that this is checking only for the using decl
8240/// itself, not for any ill-formedness among the UsingShadowDecls.
8241bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008242 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008243 const CXXScopeSpec &SS,
8244 SourceLocation NameLoc,
8245 const LookupResult &Prev) {
8246 // C++03 [namespace.udecl]p8:
8247 // C++0x [namespace.udecl]p10:
8248 // A using-declaration is a declaration and can therefore be used
8249 // repeatedly where (and only where) multiple declarations are
8250 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008251 //
John McCall032092f2010-11-29 18:01:58 +00008252 // That's in non-member contexts.
8253 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008254 return false;
8255
Aaron Ballman4a979672014-01-03 13:56:08 +00008256 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008257
8258 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8259 NamedDecl *D = *I;
8260
8261 bool DTypename;
8262 NestedNameSpecifier *DQual;
8263 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008264 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008265 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008266 } else if (UnresolvedUsingValueDecl *UD
8267 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8268 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008269 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008270 } else if (UnresolvedUsingTypenameDecl *UD
8271 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8272 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008273 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008274 } else continue;
8275
8276 // using decls differ if one says 'typename' and the other doesn't.
8277 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008278 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008279
8280 // using decls differ if they name different scopes (but note that
8281 // template instantiation can cause this check to trigger when it
8282 // didn't before instantiation).
8283 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8284 Context.getCanonicalNestedNameSpecifier(DQual))
8285 continue;
8286
8287 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008288 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008289 return true;
8290 }
8291
8292 return false;
8293}
8294
John McCall3969e302009-12-08 07:46:18 +00008295
John McCallb96ec562009-12-04 22:46:56 +00008296/// Checks that the given nested-name qualifier used in a using decl
8297/// in the current context is appropriately related to the current
8298/// scope. If an error is found, diagnoses it and returns true.
8299bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8300 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008301 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008302 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008303 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008304
John McCall3969e302009-12-08 07:46:18 +00008305 if (!CurContext->isRecord()) {
8306 // C++03 [namespace.udecl]p3:
8307 // C++0x [namespace.udecl]p8:
8308 // A using-declaration for a class member shall be a member-declaration.
8309
8310 // If we weren't able to compute a valid scope, it must be a
8311 // dependent class scope.
8312 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008313 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008314 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008315 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008316
John McCall3969e302009-12-08 07:46:18 +00008317 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8318 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008319
8320 // If we have a complete, non-dependent source type, try to suggest a
8321 // way to get the same effect.
8322 if (!RD)
8323 return true;
8324
8325 // Find what this using-declaration was referring to.
8326 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8327 R.setHideTags(false);
8328 R.suppressDiagnostics();
8329 LookupQualifiedName(R, RD);
8330
8331 if (R.getAsSingle<TypeDecl>()) {
8332 if (getLangOpts().CPlusPlus11) {
8333 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8334 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8335 << 0 // alias declaration
8336 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8337 NameInfo.getName().getAsString() +
8338 " = ");
8339 } else {
8340 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8341 SourceLocation InsertLoc =
8342 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8343 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8344 << 1 // typedef declaration
8345 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8346 << FixItHint::CreateInsertion(
8347 InsertLoc, " " + NameInfo.getName().getAsString());
8348 }
8349 } else if (R.getAsSingle<VarDecl>()) {
8350 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8351 // repeating the type of the static data member here.
8352 FixItHint FixIt;
8353 if (getLangOpts().CPlusPlus11) {
8354 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8355 FixIt = FixItHint::CreateReplacement(
8356 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8357 }
8358
8359 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8360 << 2 // reference declaration
8361 << FixIt;
8362 }
John McCall3969e302009-12-08 07:46:18 +00008363 return true;
8364 }
8365
8366 // Otherwise, everything is known to be fine.
8367 return false;
8368 }
8369
8370 // The current scope is a record.
8371
8372 // If the named context is dependent, we can't decide much.
8373 if (!NamedContext) {
8374 // FIXME: in C++0x, we can diagnose if we can prove that the
8375 // nested-name-specifier does not refer to a base class, which is
8376 // still possible in some cases.
8377
8378 // Otherwise we have to conservatively report that things might be
8379 // okay.
8380 return false;
8381 }
8382
8383 if (!NamedContext->isRecord()) {
8384 // Ideally this would point at the last name in the specifier,
8385 // but we don't have that level of source info.
8386 Diag(SS.getRange().getBegin(),
8387 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008388 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008389 return true;
8390 }
8391
Douglas Gregor7c842292010-12-21 07:41:49 +00008392 if (!NamedContext->isDependentContext() &&
8393 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8394 return true;
8395
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008396 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008397 // C++0x [namespace.udecl]p3:
8398 // In a using-declaration used as a member-declaration, the
8399 // nested-name-specifier shall name a base class of the class
8400 // being defined.
8401
8402 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8403 cast<CXXRecordDecl>(NamedContext))) {
8404 if (CurContext == NamedContext) {
8405 Diag(NameLoc,
8406 diag::err_using_decl_nested_name_specifier_is_current_class)
8407 << SS.getRange();
8408 return true;
8409 }
8410
8411 Diag(SS.getRange().getBegin(),
8412 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008413 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008414 << cast<CXXRecordDecl>(CurContext)
8415 << SS.getRange();
8416 return true;
8417 }
8418
8419 return false;
8420 }
8421
8422 // C++03 [namespace.udecl]p4:
8423 // A using-declaration used as a member-declaration shall refer
8424 // to a member of a base class of the class being defined [etc.].
8425
8426 // Salient point: SS doesn't have to name a base class as long as
8427 // lookup only finds members from base classes. Therefore we can
8428 // diagnose here only if we can prove that that can't happen,
8429 // i.e. if the class hierarchies provably don't intersect.
8430
8431 // TODO: it would be nice if "definitely valid" results were cached
8432 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8433 // need to be repeated.
8434
8435 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008436 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008437
8438 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8439 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8440 Data->Bases.insert(Base);
8441 return true;
8442 }
8443
8444 bool hasDependentBases(const CXXRecordDecl *Class) {
8445 return !Class->forallBases(collect, this);
8446 }
8447
8448 /// Returns true if the base is dependent or is one of the
8449 /// accumulated base classes.
8450 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8451 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8452 return !Data->Bases.count(Base);
8453 }
8454
8455 bool mightShareBases(const CXXRecordDecl *Class) {
8456 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8457 }
8458 };
8459
8460 UserData Data;
8461
8462 // Returns false if we find a dependent base.
8463 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8464 return false;
8465
8466 // Returns false if the class has a dependent base or if it or one
8467 // of its bases is present in the base set of the current context.
8468 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8469 return false;
8470
8471 Diag(SS.getRange().getBegin(),
8472 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008473 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008474 << cast<CXXRecordDecl>(CurContext)
8475 << SS.getRange();
8476
8477 return true;
John McCallb96ec562009-12-04 22:46:56 +00008478}
8479
Richard Smithdda56e42011-04-15 14:24:37 +00008480Decl *Sema::ActOnAliasDeclaration(Scope *S,
8481 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008482 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008483 SourceLocation UsingLoc,
8484 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008485 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008486 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008487 // Skip up to the relevant declaration scope.
8488 while (S->getFlags() & Scope::TemplateParamScope)
8489 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008490 assert((S->getFlags() & Scope::DeclScope) &&
8491 "got alias-declaration outside of declaration scope");
8492
8493 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008494 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008495
8496 bool Invalid = false;
8497 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008498 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008499 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008500
8501 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008502 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008503
8504 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008505 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008506 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008507 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8508 TInfo->getTypeLoc().getBeginLoc());
8509 }
Richard Smithdda56e42011-04-15 14:24:37 +00008510
8511 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8512 LookupName(Previous, S);
8513
8514 // Warn about shadowing the name of a template parameter.
8515 if (Previous.isSingleResult() &&
8516 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008517 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008518 Previous.clear();
8519 }
8520
8521 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8522 "name in alias declaration must be an identifier");
8523 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8524 Name.StartLocation,
8525 Name.Identifier, TInfo);
8526
8527 NewTD->setAccess(AS);
8528
8529 if (Invalid)
8530 NewTD->setInvalidDecl();
8531
Richard Smith54ecd982013-02-20 19:22:51 +00008532 ProcessDeclAttributeList(S, NewTD, AttrList);
8533
Richard Smith3f1b5d02011-05-05 21:57:07 +00008534 CheckTypedefForVariablyModifiedType(S, NewTD);
8535 Invalid |= NewTD->isInvalidDecl();
8536
Richard Smithdda56e42011-04-15 14:24:37 +00008537 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008538
8539 NamedDecl *NewND;
8540 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008541 TypeAliasTemplateDecl *OldDecl = nullptr;
8542 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008543
8544 if (TemplateParamLists.size() != 1) {
8545 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008546 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8547 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008548 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008549 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008550
8551 // Only consider previous declarations in the same scope.
8552 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8553 /*ExplicitInstantiationOrSpecialization*/false);
8554 if (!Previous.empty()) {
8555 Redeclaration = true;
8556
8557 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8558 if (!OldDecl && !Invalid) {
8559 Diag(UsingLoc, diag::err_redefinition_different_kind)
8560 << Name.Identifier;
8561
8562 NamedDecl *OldD = Previous.getRepresentativeDecl();
8563 if (OldD->getLocation().isValid())
8564 Diag(OldD->getLocation(), diag::note_previous_definition);
8565
8566 Invalid = true;
8567 }
8568
8569 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8570 if (TemplateParameterListsAreEqual(TemplateParams,
8571 OldDecl->getTemplateParameters(),
8572 /*Complain=*/true,
8573 TPL_TemplateMatch))
8574 OldTemplateParams = OldDecl->getTemplateParameters();
8575 else
8576 Invalid = true;
8577
8578 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8579 if (!Invalid &&
8580 !Context.hasSameType(OldTD->getUnderlyingType(),
8581 NewTD->getUnderlyingType())) {
8582 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8583 // but we can't reasonably accept it.
8584 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8585 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8586 if (OldTD->getLocation().isValid())
8587 Diag(OldTD->getLocation(), diag::note_previous_definition);
8588 Invalid = true;
8589 }
8590 }
8591 }
8592
8593 // Merge any previous default template arguments into our parameters,
8594 // and check the parameter list.
8595 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8596 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008597 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008598
8599 TypeAliasTemplateDecl *NewDecl =
8600 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8601 Name.Identifier, TemplateParams,
8602 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008603 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008604
8605 NewDecl->setAccess(AS);
8606
8607 if (Invalid)
8608 NewDecl->setInvalidDecl();
8609 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008610 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008611
8612 NewND = NewDecl;
8613 } else {
8614 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8615 NewND = NewTD;
8616 }
Richard Smithdda56e42011-04-15 14:24:37 +00008617
8618 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008619 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008620
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008621 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008622 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008623}
8624
Richard Smithf4634362014-09-03 23:11:22 +00008625Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8626 SourceLocation AliasLoc,
8627 IdentifierInfo *Alias, CXXScopeSpec &SS,
8628 SourceLocation IdentLoc,
8629 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008630
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008631 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008632 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8633 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008634
John McCall27b18f82009-11-17 02:14:36 +00008635 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008636 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008637
John McCall9f3059a2009-10-09 21:13:30 +00008638 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008639 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008640 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008641 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008642 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008643 }
Richard Smithf4634362014-09-03 23:11:22 +00008644 assert(!R.isAmbiguous() && !R.empty());
8645
8646 // Check if we have a previous declaration with the same name.
8647 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8648 ForRedeclaration);
8649 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8650 PrevDecl = nullptr;
8651
Aaron Ballman43f40102014-11-14 22:34:56 +00008652 NamedDecl *ND = R.getFoundDecl();
8653
Richard Smithf4634362014-09-03 23:11:22 +00008654 if (PrevDecl) {
8655 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8656 // We already have an alias with the same name that points to the same
8657 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008658 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008659 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8660 << Alias;
8661 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8662 << AD->getNamespace();
8663 return nullptr;
8664 }
8665 } else {
8666 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8667 ? diag::err_redefinition
8668 : diag::err_redefinition_different_kind;
8669 Diag(AliasLoc, DiagID) << Alias;
8670 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8671 return nullptr;
8672 }
8673 }
Mike Stump11289f42009-09-09 15:08:12 +00008674
Nico Riecke50e59a2014-11-24 17:29:52 +00008675 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008676 DiagnoseUseOfDecl(ND, IdentLoc);
8677
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008678 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008679 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008680 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008681 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008682 if (PrevDecl)
8683 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008684
John McCalld8d0d432010-02-16 06:53:13 +00008685 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008686 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008687}
8688
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008689Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008690Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8691 CXXMethodDecl *MD) {
8692 CXXRecordDecl *ClassDecl = MD->getParent();
8693
Douglas Gregor6d880b12010-07-01 22:31:05 +00008694 // C++ [except.spec]p14:
8695 // An implicitly declared special member function (Clause 12) shall have an
8696 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008697 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008698 if (ClassDecl->isInvalidDecl())
8699 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008700
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008701 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008702 for (const auto &B : ClassDecl->bases()) {
8703 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008704 continue;
8705
Aaron Ballman574705e2014-03-13 15:41:46 +00008706 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008708 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8709 // If this is a deleted function, add it anyway. This might be conformant
8710 // with the standard. This might not. I'm not sure. It might not matter.
8711 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008712 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008713 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008714 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008715
8716 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008717 for (const auto &B : ClassDecl->vbases()) {
8718 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008719 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008720 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8721 // If this is a deleted function, add it anyway. This might be conformant
8722 // with the standard. This might not. I'm not sure. It might not matter.
8723 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008724 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008725 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008726 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008727
8728 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008729 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008730 if (F->hasInClassInitializer()) {
8731 if (Expr *E = F->getInClassInitializer())
8732 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008733 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8737 // If this is a deleted function, add it anyway. This might be conformant
8738 // with the standard. This might not. I'm not sure. It might not matter.
8739 // In particular, the problem is that this function never gets called. It
8740 // might just be ill-formed because this function attempts to refer to
8741 // a deleted function here.
8742 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008743 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008744 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008745 }
John McCalldb40c7f2010-12-14 08:05:40 +00008746
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008747 return ExceptSpec;
8748}
8749
Richard Smithc2bc61b2013-03-18 21:12:30 +00008750Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008751Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8752 CXXRecordDecl *ClassDecl = CD->getParent();
8753
8754 // C++ [except.spec]p14:
8755 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008756 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008757 if (ClassDecl->isInvalidDecl())
8758 return ExceptSpec;
8759
8760 // Inherited constructor.
8761 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8762 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8763 // FIXME: Copying or moving the parameters could add extra exceptions to the
8764 // set, as could the default arguments for the inherited constructor. This
8765 // will be addressed when we implement the resolution of core issue 1351.
8766 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8767
8768 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008769 for (const auto &B : ClassDecl->bases()) {
8770 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008771 continue;
8772
Aaron Ballman574705e2014-03-13 15:41:46 +00008773 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008774 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8775 if (BaseClassDecl == InheritedDecl)
8776 continue;
8777 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8778 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008779 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008780 }
8781 }
8782
8783 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008784 for (const auto &B : ClassDecl->vbases()) {
8785 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008786 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8787 if (BaseClassDecl == InheritedDecl)
8788 continue;
8789 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8790 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008791 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008792 }
8793 }
8794
8795 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008796 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008797 if (F->hasInClassInitializer()) {
8798 if (Expr *E = F->getInClassInitializer())
8799 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008800 } else if (const RecordType *RecordTy
8801 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8802 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8803 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8804 if (Constructor)
8805 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8806 }
8807 }
8808
Richard Smithc2bc61b2013-03-18 21:12:30 +00008809 return ExceptSpec;
8810}
8811
Richard Smith8bf22e52012-11-29 01:34:07 +00008812namespace {
8813/// RAII object to register a special member as being currently declared.
8814struct DeclaringSpecialMember {
8815 Sema &S;
8816 Sema::SpecialMemberDecl D;
8817 bool WasAlreadyBeingDeclared;
8818
8819 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8820 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008821 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008822 if (WasAlreadyBeingDeclared)
8823 // This almost never happens, but if it does, ensure that our cache
8824 // doesn't contain a stale result.
8825 S.SpecialMemberCache.clear();
8826
8827 // FIXME: Register a note to be produced if we encounter an error while
8828 // declaring the special member.
8829 }
8830 ~DeclaringSpecialMember() {
8831 if (!WasAlreadyBeingDeclared)
8832 S.SpecialMembersBeingDeclared.erase(D);
8833 }
8834
8835 /// \brief Are we already trying to declare this special member?
8836 bool isAlreadyBeingDeclared() const {
8837 return WasAlreadyBeingDeclared;
8838 }
8839};
8840}
8841
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008842CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8843 CXXRecordDecl *ClassDecl) {
8844 // C++ [class.ctor]p5:
8845 // A default constructor for a class X is a constructor of class X
8846 // that can be called without an argument. If there is no
8847 // user-declared constructor for class X, a default constructor is
8848 // implicitly declared. An implicitly-declared default constructor
8849 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008850 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008851 "Should not build implicit default constructor!");
8852
Richard Smith8bf22e52012-11-29 01:34:07 +00008853 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8854 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008855 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008856
Richard Smithb5800092012-06-10 05:43:50 +00008857 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8858 CXXDefaultConstructor,
8859 false);
8860
Douglas Gregor6d880b12010-07-01 22:31:05 +00008861 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008862 CanQualType ClassType
8863 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008864 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008865 DeclarationName Name
8866 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008867 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008868 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008869 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8870 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8871 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008872 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008873 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008874
8875 if (getLangOpts().CUDA) {
8876 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8877 DefaultCon,
8878 /* ConstRHS */ false,
8879 /* Diagnose */ false);
8880 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008881
8882 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008883 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008884 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008885
Richard Smith6b02d462012-12-08 08:32:28 +00008886 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8887 // constructors is easy to compute.
8888 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8889
8890 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008891 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008892
Douglas Gregor9672f922010-07-03 00:47:00 +00008893 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008894 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008895
Douglas Gregor0be31a22010-07-02 17:43:08 +00008896 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008897 PushOnScopeChains(DefaultCon, S, false);
8898 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008899
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008900 return DefaultCon;
8901}
8902
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008903void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8904 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008905 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008906 !Constructor->doesThisDeclarationHaveABody() &&
8907 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008908 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008909
Anders Carlsson423f5d82010-04-23 16:04:08 +00008910 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008911 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008912
Eli Friedmaneaf34142012-10-18 20:14:08 +00008913 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008914 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008915 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008916 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008917 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008918 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008919 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008920 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008921 }
Douglas Gregor73193272010-09-20 16:48:21 +00008922
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008923 // The exception specification is needed because we are defining the
8924 // function.
8925 ResolveExceptionSpec(CurrentLocation,
8926 Constructor->getType()->castAs<FunctionProtoType>());
8927
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008928 SourceLocation Loc = Constructor->getLocEnd().isValid()
8929 ? Constructor->getLocEnd()
8930 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008931 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008932
Eli Friedman276dd182013-09-05 00:02:25 +00008933 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008934 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008935
8936 if (ASTMutationListener *L = getASTMutationListener()) {
8937 L->CompletedImplicitDefinition(Constructor);
8938 }
Richard Trieuef64e942013-10-25 00:56:00 +00008939
8940 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008941}
8942
Richard Smith938f40b2011-06-11 17:19:42 +00008943void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008944 // Perform any delayed checks on exception specifications.
8945 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008946}
8947
Richard Smith185be182013-04-10 05:48:59 +00008948namespace {
8949/// Information on inheriting constructors to declare.
8950class InheritingConstructorInfo {
8951public:
8952 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8953 : SemaRef(SemaRef), Derived(Derived) {
8954 // Mark the constructors that we already have in the derived class.
8955 //
8956 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8957 // unless there is a user-declared constructor with the same signature in
8958 // the class where the using-declaration appears.
8959 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8960 }
8961
8962 void inheritAll(CXXRecordDecl *RD) {
8963 visitAll(RD, &InheritingConstructorInfo::inherit);
8964 }
8965
8966private:
8967 /// Information about an inheriting constructor.
8968 struct InheritingConstructor {
8969 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008970 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008971
8972 /// If \c true, a constructor with this signature is already declared
8973 /// in the derived class.
8974 bool DeclaredInDerived;
8975
8976 /// The constructor which is inherited.
8977 const CXXConstructorDecl *BaseCtor;
8978
8979 /// The derived constructor we declared.
8980 CXXConstructorDecl *DerivedCtor;
8981 };
8982
8983 /// Inheriting constructors with a given canonical type. There can be at
8984 /// most one such non-template constructor, and any number of templated
8985 /// constructors.
8986 struct InheritingConstructorsForType {
8987 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008988 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8989 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008990
8991 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8992 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8993 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8994 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8995 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8996 false, S.TPL_TemplateMatch))
8997 return Templates[I].second;
8998 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8999 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009000 }
Richard Smith185be182013-04-10 05:48:59 +00009001
9002 return NonTemplate;
9003 }
9004 };
9005
9006 /// Get or create the inheriting constructor record for a constructor.
9007 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9008 QualType CtorType) {
9009 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9010 .getEntry(SemaRef, Ctor);
9011 }
9012
9013 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9014
9015 /// Process all constructors for a class.
9016 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009017 for (const auto *Ctor : RD->ctors())
9018 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009019 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9020 I(RD->decls_begin()), E(RD->decls_end());
9021 I != E; ++I) {
9022 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9023 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9024 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009025 }
9026 }
Richard Smith185be182013-04-10 05:48:59 +00009027
9028 /// Note that a constructor (or constructor template) was declared in Derived.
9029 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9030 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9031 }
9032
9033 /// Inherit a single constructor.
9034 void inherit(const CXXConstructorDecl *Ctor) {
9035 const FunctionProtoType *CtorType =
9036 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009037 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009038 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9039
9040 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9041
9042 // Core issue (no number yet): the ellipsis is always discarded.
9043 if (EPI.Variadic) {
9044 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9045 SemaRef.Diag(Ctor->getLocation(),
9046 diag::note_using_decl_constructor_ellipsis);
9047 EPI.Variadic = false;
9048 }
9049
9050 // Declare a constructor for each number of parameters.
9051 //
9052 // C++11 [class.inhctor]p1:
9053 // The candidate set of inherited constructors from the class X named in
9054 // the using-declaration consists of [... modulo defects ...] for each
9055 // constructor or constructor template of X, the set of constructors or
9056 // constructor templates that results from omitting any ellipsis parameter
9057 // specification and successively omitting parameters with a default
9058 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009059 unsigned MinParams = minParamsToInherit(Ctor);
9060 unsigned Params = Ctor->getNumParams();
9061 if (Params >= MinParams) {
9062 do
9063 declareCtor(UsingLoc, Ctor,
9064 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009065 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009066 while (Params > MinParams &&
9067 Ctor->getParamDecl(--Params)->hasDefaultArg());
9068 }
Richard Smith185be182013-04-10 05:48:59 +00009069 }
9070
9071 /// Find the using-declaration which specified that we should inherit the
9072 /// constructors of \p Base.
9073 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9074 // No fancy lookup required; just look for the base constructor name
9075 // directly within the derived class.
9076 ASTContext &Context = SemaRef.Context;
9077 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9078 Context.getCanonicalType(Context.getRecordType(Base)));
9079 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9080 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9081 }
9082
9083 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9084 // C++11 [class.inhctor]p3:
9085 // [F]or each constructor template in the candidate set of inherited
9086 // constructors, a constructor template is implicitly declared
9087 if (Ctor->getDescribedFunctionTemplate())
9088 return 0;
9089
9090 // For each non-template constructor in the candidate set of inherited
9091 // constructors other than a constructor having no parameters or a
9092 // copy/move constructor having a single parameter, a constructor is
9093 // implicitly declared [...]
9094 if (Ctor->getNumParams() == 0)
9095 return 1;
9096 if (Ctor->isCopyOrMoveConstructor())
9097 return 2;
9098
9099 // Per discussion on core reflector, never inherit a constructor which
9100 // would become a default, copy, or move constructor of Derived either.
9101 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9102 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9103 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9104 }
9105
9106 /// Declare a single inheriting constructor, inheriting the specified
9107 /// constructor, with the given type.
9108 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9109 QualType DerivedType) {
9110 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9111
9112 // C++11 [class.inhctor]p3:
9113 // ... a constructor is implicitly declared with the same constructor
9114 // characteristics unless there is a user-declared constructor with
9115 // the same signature in the class where the using-declaration appears
9116 if (Entry.DeclaredInDerived)
9117 return;
9118
9119 // C++11 [class.inhctor]p7:
9120 // If two using-declarations declare inheriting constructors with the
9121 // same signature, the program is ill-formed
9122 if (Entry.DerivedCtor) {
9123 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9124 // Only diagnose this once per constructor.
9125 if (Entry.DerivedCtor->isInvalidDecl())
9126 return;
9127 Entry.DerivedCtor->setInvalidDecl();
9128
9129 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9130 SemaRef.Diag(BaseCtor->getLocation(),
9131 diag::note_using_decl_constructor_conflict_current_ctor);
9132 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9133 diag::note_using_decl_constructor_conflict_previous_ctor);
9134 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9135 diag::note_using_decl_constructor_conflict_previous_using);
9136 } else {
9137 // Core issue (no number): if the same inheriting constructor is
9138 // produced by multiple base class constructors from the same base
9139 // class, the inheriting constructor is defined as deleted.
9140 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9141 }
9142
9143 return;
9144 }
9145
9146 ASTContext &Context = SemaRef.Context;
9147 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9148 Context.getCanonicalType(Context.getRecordType(Derived)));
9149 DeclarationNameInfo NameInfo(Name, UsingLoc);
9150
Craig Topperc3ec1492014-05-26 06:22:03 +00009151 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009152 if (const FunctionTemplateDecl *FTD =
9153 BaseCtor->getDescribedFunctionTemplate()) {
9154 TemplateParams = FTD->getTemplateParameters();
9155 // We're reusing template parameters from a different DeclContext. This
9156 // is questionable at best, but works out because the template depth in
9157 // both places is guaranteed to be 0.
9158 // FIXME: Rebuild the template parameters in the new context, and
9159 // transform the function type to refer to them.
9160 }
9161
9162 // Build type source info pointing at the using-declaration. This is
9163 // required by template instantiation.
9164 TypeSourceInfo *TInfo =
9165 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9166 FunctionProtoTypeLoc ProtoLoc =
9167 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9168
9169 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9170 Context, Derived, UsingLoc, NameInfo, DerivedType,
9171 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9172 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9173
9174 // Build an unevaluated exception specification for this constructor.
9175 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9176 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009177 EPI.ExceptionSpec.Type = EST_Unevaluated;
9178 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009179 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009180 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009181
9182 // Build the parameter declarations.
9183 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009184 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009185 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009186 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009187 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009188 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9189 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009190 PD->setScopeInfo(0, I);
9191 PD->setImplicit();
9192 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009193 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009194 }
9195
9196 // Set up the new constructor.
9197 DerivedCtor->setAccess(BaseCtor->getAccess());
9198 DerivedCtor->setParams(ParamDecls);
9199 DerivedCtor->setInheritedConstructor(BaseCtor);
9200 if (BaseCtor->isDeleted())
9201 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9202
9203 // If this is a constructor template, build the template declaration.
9204 if (TemplateParams) {
9205 FunctionTemplateDecl *DerivedTemplate =
9206 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9207 TemplateParams, DerivedCtor);
9208 DerivedTemplate->setAccess(BaseCtor->getAccess());
9209 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9210 Derived->addDecl(DerivedTemplate);
9211 } else {
9212 Derived->addDecl(DerivedCtor);
9213 }
9214
9215 Entry.BaseCtor = BaseCtor;
9216 Entry.DerivedCtor = DerivedCtor;
9217 }
9218
9219 Sema &SemaRef;
9220 CXXRecordDecl *Derived;
9221 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9222 MapType Map;
9223};
9224}
9225
9226void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9227 // Defer declaring the inheriting constructors until the class is
9228 // instantiated.
9229 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009230 return;
9231
Richard Smith185be182013-04-10 05:48:59 +00009232 // Find base classes from which we might inherit constructors.
9233 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009234 for (const auto &BaseIt : ClassDecl->bases())
9235 if (BaseIt.getInheritConstructors())
9236 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009237
Richard Smith185be182013-04-10 05:48:59 +00009238 // Go no further if we're not inheriting any constructors.
9239 if (InheritedBases.empty())
9240 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009241
Richard Smith185be182013-04-10 05:48:59 +00009242 // Declare the inherited constructors.
9243 InheritingConstructorInfo ICI(*this, ClassDecl);
9244 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9245 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009246}
9247
Richard Smithc2bc61b2013-03-18 21:12:30 +00009248void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9249 CXXConstructorDecl *Constructor) {
9250 CXXRecordDecl *ClassDecl = Constructor->getParent();
9251 assert(Constructor->getInheritedConstructor() &&
9252 !Constructor->doesThisDeclarationHaveABody() &&
9253 !Constructor->isDeleted());
9254
9255 SynthesizedFunctionScope Scope(*this, Constructor);
9256 DiagnosticErrorTrap Trap(Diags);
9257 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9258 Trap.hasErrorOccurred()) {
9259 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9260 << Context.getTagDeclType(ClassDecl);
9261 Constructor->setInvalidDecl();
9262 return;
9263 }
9264
9265 SourceLocation Loc = Constructor->getLocation();
9266 Constructor->setBody(new (Context) CompoundStmt(Loc));
9267
Eli Friedman276dd182013-09-05 00:02:25 +00009268 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009269 MarkVTableUsed(CurrentLocation, ClassDecl);
9270
9271 if (ASTMutationListener *L = getASTMutationListener()) {
9272 L->CompletedImplicitDefinition(Constructor);
9273 }
9274}
9275
9276
Alexis Huntf91729462011-05-12 22:46:25 +00009277Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009278Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9279 CXXRecordDecl *ClassDecl = MD->getParent();
9280
Douglas Gregorf1203042010-07-01 19:09:28 +00009281 // C++ [except.spec]p14:
9282 // An implicitly declared special member function (Clause 12) shall have
9283 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009284 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009285 if (ClassDecl->isInvalidDecl())
9286 return ExceptSpec;
9287
Douglas Gregorf1203042010-07-01 19:09:28 +00009288 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009289 for (const auto &B : ClassDecl->bases()) {
9290 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009291 continue;
9292
Aaron Ballman574705e2014-03-13 15:41:46 +00009293 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9294 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009295 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009296 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009297
Douglas Gregorf1203042010-07-01 19:09:28 +00009298 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009299 for (const auto &B : ClassDecl->vbases()) {
9300 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9301 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009302 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009303 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009304
Douglas Gregorf1203042010-07-01 19:09:28 +00009305 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009306 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009307 if (const RecordType *RecordTy
9308 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009309 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009310 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009311 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009312
Alexis Huntf91729462011-05-12 22:46:25 +00009313 return ExceptSpec;
9314}
9315
9316CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9317 // C++ [class.dtor]p2:
9318 // If a class has no user-declared destructor, a destructor is
9319 // declared implicitly. An implicitly-declared destructor is an
9320 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009321 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009322
Richard Smith8bf22e52012-11-29 01:34:07 +00009323 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9324 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009325 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009326
Douglas Gregor7454c562010-07-02 20:37:36 +00009327 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009328 CanQualType ClassType
9329 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009330 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009331 DeclarationName Name
9332 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009333 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009334 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009335 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009336 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009337 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009338 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009339 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009340
9341 if (getLangOpts().CUDA) {
9342 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9343 Destructor,
9344 /* ConstRHS */ false,
9345 /* Diagnose */ false);
9346 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009347
9348 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009349 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009350 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009351
Richard Smith6b02d462012-12-08 08:32:28 +00009352 AddOverriddenMethods(ClassDecl, Destructor);
9353
9354 // We don't need to use SpecialMemberIsTrivial here; triviality for
9355 // destructors is easy to compute.
9356 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9357
9358 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009359 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009360
Douglas Gregor7454c562010-07-02 20:37:36 +00009361 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009362 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009363
Douglas Gregor7454c562010-07-02 20:37:36 +00009364 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009365 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009366 PushOnScopeChains(Destructor, S, false);
9367 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009368
Douglas Gregorf1203042010-07-01 19:09:28 +00009369 return Destructor;
9370}
9371
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009372void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009373 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009374 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009375 !Destructor->doesThisDeclarationHaveABody() &&
9376 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009377 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009378 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009379 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009380
Douglas Gregor54818f02010-05-12 16:39:35 +00009381 if (Destructor->isInvalidDecl())
9382 return;
9383
Eli Friedmaneaf34142012-10-18 20:14:08 +00009384 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009385
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009386 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009387 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9388 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009389
Douglas Gregor54818f02010-05-12 16:39:35 +00009390 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009391 Diag(CurrentLocation, diag::note_member_synthesized_at)
9392 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9393
9394 Destructor->setInvalidDecl();
9395 return;
9396 }
9397
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009398 // The exception specification is needed because we are defining the
9399 // function.
9400 ResolveExceptionSpec(CurrentLocation,
9401 Destructor->getType()->castAs<FunctionProtoType>());
9402
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009403 SourceLocation Loc = Destructor->getLocEnd().isValid()
9404 ? Destructor->getLocEnd()
9405 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009406 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009407 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009408 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009409
9410 if (ASTMutationListener *L = getASTMutationListener()) {
9411 L->CompletedImplicitDefinition(Destructor);
9412 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009413}
9414
Richard Smith84973e52012-04-21 18:42:51 +00009415/// \brief Perform any semantic analysis which needs to be delayed until all
9416/// pending class member declarations have been parsed.
9417void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009418 // If the context is an invalid C++ class, just suppress these checks.
9419 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9420 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009421 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009422 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009423 return;
9424 }
9425 }
Richard Smith84973e52012-04-21 18:42:51 +00009426}
9427
Richard Smithd3b5c9082012-07-27 04:22:15 +00009428void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9429 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009430 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009431 "adjusting dtor exception specs was introduced in c++11");
9432
Sebastian Redl623ea822011-05-19 05:13:44 +00009433 // C++11 [class.dtor]p3:
9434 // A declaration of a destructor that does not have an exception-
9435 // specification is implicitly considered to have the same exception-
9436 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009437 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009438 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009439 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009440 return;
9441
Chandler Carruth9a797572011-09-20 04:55:26 +00009442 // Replace the destructor's type, building off the existing one. Fortunately,
9443 // the only thing of interest in the destructor type is its extended info.
9444 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009445 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009446 EPI.ExceptionSpec.Type = EST_Unevaluated;
9447 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009448 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009449
Sebastian Redl623ea822011-05-19 05:13:44 +00009450 // FIXME: If the destructor has a body that could throw, and the newly created
9451 // spec doesn't allow exceptions, we should emit a warning, because this
9452 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009453 // However, we don't have a body or an exception specification yet, so it
9454 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009455}
9456
Pavel Labath58934982013-08-30 08:52:28 +00009457namespace {
9458/// \brief An abstract base class for all helper classes used in building the
9459// copy/move operators. These classes serve as factory functions and help us
9460// avoid using the same Expr* in the AST twice.
9461class ExprBuilder {
9462 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9463 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9464
9465protected:
9466 static Expr *assertNotNull(Expr *E) {
9467 assert(E && "Expression construction must not fail.");
9468 return E;
9469 }
9470
9471public:
9472 ExprBuilder() {}
9473 virtual ~ExprBuilder() {}
9474
9475 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9476};
9477
9478class RefBuilder: public ExprBuilder {
9479 VarDecl *Var;
9480 QualType VarType;
9481
9482public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009483 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009484 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009485 }
9486
9487 RefBuilder(VarDecl *Var, QualType VarType)
9488 : Var(Var), VarType(VarType) {}
9489};
9490
9491class ThisBuilder: public ExprBuilder {
9492public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009493 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009494 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009495 }
9496};
9497
9498class CastBuilder: public ExprBuilder {
9499 const ExprBuilder &Builder;
9500 QualType Type;
9501 ExprValueKind Kind;
9502 const CXXCastPath &Path;
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(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9507 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009508 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009509 }
9510
9511 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9512 const CXXCastPath &Path)
9513 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9514};
9515
9516class DerefBuilder: public ExprBuilder {
9517 const ExprBuilder &Builder;
9518
9519public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009520 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009521 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009522 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009523 }
9524
9525 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9526};
9527
9528class MemberBuilder: public ExprBuilder {
9529 const ExprBuilder &Builder;
9530 QualType Type;
9531 CXXScopeSpec SS;
9532 bool IsArrow;
9533 LookupResult &MemberLookup;
9534
9535public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009536 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009537 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009538 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009539 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009540 }
9541
9542 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9543 LookupResult &MemberLookup)
9544 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9545 MemberLookup(MemberLookup) {}
9546};
9547
9548class MoveCastBuilder: public ExprBuilder {
9549 const ExprBuilder &Builder;
9550
9551public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009552 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009553 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9554 }
9555
9556 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9557};
9558
9559class LvalueConvBuilder: public ExprBuilder {
9560 const ExprBuilder &Builder;
9561
9562public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009563 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009564 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009565 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009566 }
9567
9568 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9569};
9570
9571class SubscriptBuilder: public ExprBuilder {
9572 const ExprBuilder &Base;
9573 const ExprBuilder &Index;
9574
9575public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009576 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009577 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009578 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009579 }
9580
9581 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9582 : Base(Base), Index(Index) {}
9583};
9584
9585} // end anonymous namespace
9586
Richard Smith41ae3282012-11-14 00:50:40 +00009587/// When generating a defaulted copy or move assignment operator, if a field
9588/// should be copied with __builtin_memcpy rather than via explicit assignments,
9589/// do so. This optimization only applies for arrays of scalars, and for arrays
9590/// of class type where the selected copy/move-assignment operator is trivial.
9591static StmtResult
9592buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009593 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009594 // Compute the size of the memory buffer to be copied.
9595 QualType SizeType = S.Context.getSizeType();
9596 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9597 S.Context.getTypeSizeInChars(T).getQuantity());
9598
9599 // Take the address of the field references for "from" and "to". We
9600 // directly construct UnaryOperators here because semantic analysis
9601 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009602 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009603 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9604 S.Context.getPointerType(From->getType()),
9605 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009606 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009607 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9608 S.Context.getPointerType(To->getType()),
9609 VK_RValue, OK_Ordinary, Loc);
9610
9611 const Type *E = T->getBaseElementTypeUnsafe();
9612 bool NeedsCollectableMemCpy =
9613 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9614
9615 // Create a reference to the __builtin_objc_memmove_collectable function
9616 StringRef MemCpyName = NeedsCollectableMemCpy ?
9617 "__builtin_objc_memmove_collectable" :
9618 "__builtin_memcpy";
9619 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9620 Sema::LookupOrdinaryName);
9621 S.LookupName(R, S.TUScope, true);
9622
9623 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9624 if (!MemCpy)
9625 // Something went horribly wrong earlier, and we will have complained
9626 // about it.
9627 return StmtError();
9628
9629 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009630 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009631 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9632
9633 Expr *CallArgs[] = {
9634 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9635 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009636 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009637 Loc, CallArgs, Loc);
9638
9639 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009640 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009641}
9642
Sebastian Redl22653ba2011-08-30 19:58:05 +00009643/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009644/// \c To.
9645///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009646/// This routine is used to copy/move the members of a class with an
9647/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009648/// copied are arrays, this routine builds for loops to copy them.
9649///
9650/// \param S The Sema object used for type-checking.
9651///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009653///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009654/// \param T The type of the expressions being copied/moved. Both expressions
9655/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009656///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009657/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009658///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009659/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009660///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009661/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009662/// Otherwise, it's a non-static member subobject.
9663///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009664/// \param Copying Whether we're copying or moving.
9665///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009666/// \param Depth Internal parameter recording the depth of the recursion.
9667///
Richard Smith41ae3282012-11-14 00:50:40 +00009668/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9669/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009670static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009671buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009672 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009673 bool CopyingBaseSubobject, bool Copying,
9674 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009675 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009676 // Each subobject is assigned in the manner appropriate to its type:
9677 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009678 // - if the subobject is of class type, as if by a call to operator= with
9679 // the subobject as the object expression and the corresponding
9680 // subobject of x as a single function argument (as if by explicit
9681 // qualification; that is, ignoring any possible virtual overriding
9682 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009683 //
9684 // C++03 [class.copy]p13:
9685 // - if the subobject is of class type, the copy assignment operator for
9686 // the class is used (as if by explicit qualification; that is,
9687 // ignoring any possible virtual overriding functions in more derived
9688 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009689 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9690 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009691
Douglas Gregorb139cd52010-05-01 20:49:11 +00009692 // Look for operator=.
9693 DeclarationName Name
9694 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9695 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9696 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009697
Richard Smith52c0b582012-11-13 00:54:12 +00009698 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9699 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009700 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009701 LookupResult::Filter F = OpLookup.makeFilter();
9702 while (F.hasNext()) {
9703 NamedDecl *D = F.next();
9704 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9705 if (Method->isCopyAssignmentOperator() ||
9706 (!Copying && Method->isMoveAssignmentOperator()))
9707 continue;
9708
9709 F.erase();
9710 }
9711 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009712 }
Richard Smith52c0b582012-11-13 00:54:12 +00009713
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009714 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009715 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009716 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009717 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009718 // ambiguities), we need to cast "this" to that subobject type; to
9719 // ensure that we don't go through the virtual call mechanism, we need
9720 // to qualify the operator= name with the base class (see below). However,
9721 // this means that if the base class has a protected copy assignment
9722 // operator, the protected member access check will fail. So, we
9723 // rewrite "protected" access to "public" access in this case, since we
9724 // know by construction that we're calling from a derived class.
9725 if (CopyingBaseSubobject) {
9726 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9727 L != LEnd; ++L) {
9728 if (L.getAccess() == AS_protected)
9729 L.setAccess(AS_public);
9730 }
9731 }
Richard Smith52c0b582012-11-13 00:54:12 +00009732
Douglas Gregorb139cd52010-05-01 20:49:11 +00009733 // Create the nested-name-specifier that will be used to qualify the
9734 // reference to operator=; this is required to suppress the virtual
9735 // call mechanism.
9736 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009737 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009738 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009739 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009740 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009741 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009742
Douglas Gregorb139cd52010-05-01 20:49:11 +00009743 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009744 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009745 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9746 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009747 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009748 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009749 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009750 /*SuppressQualifierCheck=*/true);
9751 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009752 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009753
Douglas Gregorb139cd52010-05-01 20:49:11 +00009754 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009755
Pavel Labath58934982013-08-30 08:52:28 +00009756 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009757 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009758 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009759 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009760 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009761 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009762
Richard Smith41ae3282012-11-14 00:50:40 +00009763 // If we built a call to a trivial 'operator=' while copying an array,
9764 // bail out. We'll replace the whole shebang with a memcpy.
9765 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9766 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009767 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009768
Richard Smith52c0b582012-11-13 00:54:12 +00009769 // Convert to an expression-statement, and clean up any produced
9770 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009771 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009772 }
John McCallab8c2732010-03-16 06:11:48 +00009773
Richard Smith52c0b582012-11-13 00:54:12 +00009774 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009775 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009776 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009777 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009778 ExprResult Assignment = S.CreateBuiltinBinOp(
9779 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009780 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009781 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009782 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009783 }
Richard Smith52c0b582012-11-13 00:54:12 +00009784
9785 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009786 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009787
Douglas Gregorb139cd52010-05-01 20:49:11 +00009788 // Construct a loop over the array bounds, e.g.,
9789 //
9790 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9791 //
9792 // that will copy each of the array elements.
9793 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009794
Douglas Gregorb139cd52010-05-01 20:49:11 +00009795 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009796 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009797 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009798 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009799 llvm::raw_svector_ostream OS(Str);
9800 OS << "__i" << Depth;
9801 IterationVarName = &S.Context.Idents.get(OS.str());
9802 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009803 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009804 IterationVarName, SizeType,
9805 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009806 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009807
Douglas Gregorb139cd52010-05-01 20:49:11 +00009808 // Initialize the iteration variable to zero.
9809 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009810 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009811
Pavel Labath58934982013-08-30 08:52:28 +00009812 // Creates a reference to the iteration variable.
9813 RefBuilder IterationVarRef(IterationVar, SizeType);
9814 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009815
Douglas Gregorb139cd52010-05-01 20:49:11 +00009816 // Create the DeclStmt that holds the iteration variable.
9817 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009818
Douglas Gregorb139cd52010-05-01 20:49:11 +00009819 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009820 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9821 MoveCastBuilder FromIndexMove(FromIndexCopy);
9822 const ExprBuilder *FromIndex;
9823 if (Copying)
9824 FromIndex = &FromIndexCopy;
9825 else
9826 FromIndex = &FromIndexMove;
9827
9828 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009829
9830 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009831 StmtResult Copy =
9832 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009833 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009834 Copying, Depth + 1);
9835 // Bail out if copying fails or if we determined that we should use memcpy.
9836 if (Copy.isInvalid() || !Copy.get())
9837 return Copy;
9838
9839 // Create the comparison against the array bound.
9840 llvm::APInt Upper
9841 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9842 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009843 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009844 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9845 BO_NE, S.Context.BoolTy,
9846 VK_RValue, OK_Ordinary, Loc, false);
9847
9848 // Create the pre-increment of the iteration variable.
9849 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009850 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9851 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009852
Douglas Gregorb139cd52010-05-01 20:49:11 +00009853 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009854 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009855 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009856 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009857 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009858}
9859
Richard Smith41ae3282012-11-14 00:50:40 +00009860static StmtResult
9861buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009862 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009863 bool CopyingBaseSubobject, bool Copying) {
9864 // Maybe we should use a memcpy?
9865 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9866 T.isTriviallyCopyableType(S.Context))
9867 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9868
9869 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9870 CopyingBaseSubobject,
9871 Copying, 0));
9872
9873 // If we ended up picking a trivial assignment operator for an array of a
9874 // non-trivially-copyable class type, just emit a memcpy.
9875 if (!Result.isInvalid() && !Result.get())
9876 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9877
9878 return Result;
9879}
9880
Richard Smithd3b5c9082012-07-27 04:22:15 +00009881Sema::ImplicitExceptionSpecification
9882Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9883 CXXRecordDecl *ClassDecl = MD->getParent();
9884
9885 ImplicitExceptionSpecification ExceptSpec(*this);
9886 if (ClassDecl->isInvalidDecl())
9887 return ExceptSpec;
9888
9889 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009890 assert(T->getNumParams() == 1 && "not a copy assignment op");
9891 unsigned ArgQuals =
9892 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009893
Douglas Gregor68e11362010-07-01 17:48:08 +00009894 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009895 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009896 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009897
9898 // It is unspecified whether or not an implicit copy assignment operator
9899 // attempts to deduplicate calls to assignment operators of virtual bases are
9900 // made. As such, this exception specification is effectively unspecified.
9901 // Based on a similar decision made for constness in C++0x, we're erring on
9902 // the side of assuming such calls to be made regardless of whether they
9903 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009904 for (const auto &Base : ClassDecl->bases()) {
9905 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009906 continue;
9907
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009908 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009909 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009910 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9911 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009912 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009913 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009914
Aaron Ballman445a9392014-03-13 16:15:17 +00009915 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009916 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009917 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009918 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9919 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009920 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009921 }
9922
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009923 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009924 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009925 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9926 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009927 LookupCopyingAssignment(FieldClassDecl,
9928 ArgQuals | FieldType.getCVRQualifiers(),
9929 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009930 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009931 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009932 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009933
Richard Smithd3b5c9082012-07-27 04:22:15 +00009934 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009935}
9936
9937CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9938 // Note: The following rules are largely analoguous to the copy
9939 // constructor rules. Note that virtual bases are not taken into account
9940 // for determining the argument type of the operator. Note also that
9941 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009942 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009943
Richard Smith8bf22e52012-11-29 01:34:07 +00009944 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9945 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009946 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009947
Alexis Hunt119f3652011-05-14 05:23:20 +00009948 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9949 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009950 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9951 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009952 ArgType = ArgType.withConst();
9953 ArgType = Context.getLValueReferenceType(ArgType);
9954
Richard Smith99005e62013-05-07 03:19:20 +00009955 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9956 CXXCopyAssignment,
9957 Const);
9958
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009959 // An implicitly-declared copy assignment operator is an inline public
9960 // member of its class.
9961 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009962 SourceLocation ClassLoc = ClassDecl->getLocation();
9963 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009964 CXXMethodDecl *CopyAssignment =
9965 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009966 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9967 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009968 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009969 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009970 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009971
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009972 if (getLangOpts().CUDA) {
9973 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9974 CopyAssignment,
9975 /* ConstRHS */ Const,
9976 /* Diagnose */ false);
9977 }
9978
Richard Smithd3b5c9082012-07-27 04:22:15 +00009979 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009980 FunctionProtoType::ExtProtoInfo EPI =
9981 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009982 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009983
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009984 // Add the parameter to the operator.
9985 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009986 ClassLoc, ClassLoc,
9987 /*Id=*/nullptr, ArgType,
9988 /*TInfo=*/nullptr, SC_None,
9989 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009990 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009991
Richard Smith6b02d462012-12-08 08:32:28 +00009992 AddOverriddenMethods(ClassDecl, CopyAssignment);
9993
9994 CopyAssignment->setTrivial(
9995 ClassDecl->needsOverloadResolutionForCopyAssignment()
9996 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9997 : ClassDecl->hasTrivialCopyAssignment());
9998
Richard Smith852265f2012-03-30 20:53:28 +00009999 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010000 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010001
Richard Smith6b02d462012-12-08 08:32:28 +000010002 // Note that we have added this copy-assignment operator.
10003 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10004
10005 if (Scope *S = getScopeForContext(ClassDecl))
10006 PushOnScopeChains(CopyAssignment, S, false);
10007 ClassDecl->addDecl(CopyAssignment);
10008
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010009 return CopyAssignment;
10010}
10011
Richard Smithd577fbb2013-06-13 03:23:42 +000010012/// Diagnose an implicit copy operation for a class which is odr-used, but
10013/// which is deprecated because the class has a user-declared copy constructor,
10014/// copy assignment operator, or destructor.
10015static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10016 SourceLocation UseLoc) {
10017 assert(CopyOp->isImplicit());
10018
10019 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010020 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010021
10022 // In Microsoft mode, assignment operations don't affect constructors and
10023 // vice versa.
10024 if (RD->hasUserDeclaredDestructor()) {
10025 UserDeclaredOperation = RD->getDestructor();
10026 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10027 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010028 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010029 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010030 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010031 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010032 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010033 break;
10034 }
10035 }
10036 assert(UserDeclaredOperation);
10037 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10038 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010039 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010040 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010041 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010042 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010043 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010044 break;
10045 }
10046 }
10047 assert(UserDeclaredOperation);
10048 }
10049
10050 if (UserDeclaredOperation) {
10051 S.Diag(UserDeclaredOperation->getLocation(),
10052 diag::warn_deprecated_copy_operation)
10053 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10054 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10055 S.Diag(UseLoc, diag::note_member_synthesized_at)
10056 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10057 : Sema::CXXCopyAssignment)
10058 << RD;
10059 }
10060}
10061
Douglas Gregorb139cd52010-05-01 20:49:11 +000010062void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10063 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010064 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010065 CopyAssignOperator->isOverloadedOperator() &&
10066 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010067 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10068 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010069 "DefineImplicitCopyAssignment called for wrong function");
10070
10071 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10072
10073 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10074 CopyAssignOperator->setInvalidDecl();
10075 return;
10076 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010077
10078 // C++11 [class.copy]p18:
10079 // The [definition of an implicitly declared copy assignment operator] is
10080 // deprecated if the class has a user-declared copy constructor or a
10081 // user-declared destructor.
10082 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10083 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10084
Eli Friedman276dd182013-09-05 00:02:25 +000010085 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010086
Eli Friedmaneaf34142012-10-18 20:14:08 +000010087 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010088 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010089
10090 // C++0x [class.copy]p30:
10091 // The implicitly-defined or explicitly-defaulted copy assignment operator
10092 // for a non-union class X performs memberwise copy assignment of its
10093 // subobjects. The direct base classes of X are assigned first, in the
10094 // order of their declaration in the base-specifier-list, and then the
10095 // immediate non-static data members of X are assigned, in the order in
10096 // which they were declared in the class definition.
10097
10098 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010099 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010100
10101 // The parameter for the "other" object, which we are copying from.
10102 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10103 Qualifiers OtherQuals = Other->getType().getQualifiers();
10104 QualType OtherRefType = Other->getType();
10105 if (const LValueReferenceType *OtherRef
10106 = OtherRefType->getAs<LValueReferenceType>()) {
10107 OtherRefType = OtherRef->getPointeeType();
10108 OtherQuals = OtherRefType.getQualifiers();
10109 }
10110
10111 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010112 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10113 ? CopyAssignOperator->getLocEnd()
10114 : CopyAssignOperator->getLocation();
10115
Pavel Labath58934982013-08-30 08:52:28 +000010116 // Builds a DeclRefExpr for the "other" object.
10117 RefBuilder OtherRef(Other, OtherRefType);
10118
10119 // Builds the "this" pointer.
10120 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010121
10122 // Assign base classes.
10123 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010124 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010125 // Form the assignment:
10126 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010127 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010128 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010129 Invalid = true;
10130 continue;
10131 }
10132
John McCallcf142162010-08-07 06:22:56 +000010133 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010134 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010135
Douglas Gregorb139cd52010-05-01 20:49:11 +000010136 // Construct the "from" expression, which is an implicit cast to the
10137 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010138 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10139 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010140
10141 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010142 DerefBuilder DerefThis(This);
10143 CastBuilder To(DerefThis,
10144 Context.getCVRQualifiedType(
10145 BaseType, CopyAssignOperator->getTypeQualifiers()),
10146 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010147
10148 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010149 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010150 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151 /*CopyingBaseSubobject=*/true,
10152 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010153 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010154 Diag(CurrentLocation, diag::note_member_synthesized_at)
10155 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10156 CopyAssignOperator->setInvalidDecl();
10157 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010158 }
10159
10160 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010161 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010162 }
10163
Douglas Gregorb139cd52010-05-01 20:49:11 +000010164 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010165 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010166 if (Field->isUnnamedBitfield())
10167 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010168
10169 if (Field->isInvalidDecl()) {
10170 Invalid = true;
10171 continue;
10172 }
10173
Douglas Gregorb139cd52010-05-01 20:49:11 +000010174 // Check for members of reference type; we can't copy those.
10175 if (Field->getType()->isReferenceType()) {
10176 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10177 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10178 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010179 Diag(CurrentLocation, diag::note_member_synthesized_at)
10180 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010181 Invalid = true;
10182 continue;
10183 }
10184
10185 // Check for members of const-qualified, non-class type.
10186 QualType BaseType = Context.getBaseElementType(Field->getType());
10187 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10188 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10189 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10190 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010191 Diag(CurrentLocation, diag::note_member_synthesized_at)
10192 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010193 Invalid = true;
10194 continue;
10195 }
John McCall1b1a1db2011-06-17 00:18:42 +000010196
10197 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010198 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10199 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010200
10201 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010202 if (FieldType->isIncompleteArrayType()) {
10203 assert(ClassDecl->hasFlexibleArrayMember() &&
10204 "Incomplete array type is not valid");
10205 continue;
10206 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010207
10208 // Build references to the field in the object we're copying from and to.
10209 CXXScopeSpec SS; // Intentionally empty
10210 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10211 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010212 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010213 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010214
10215 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10216
10217 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010218
Douglas Gregorb139cd52010-05-01 20:49:11 +000010219 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010220 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010221 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010222 /*CopyingBaseSubobject=*/false,
10223 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010224 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010225 Diag(CurrentLocation, diag::note_member_synthesized_at)
10226 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10227 CopyAssignOperator->setInvalidDecl();
10228 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010229 }
10230
10231 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010232 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010233 }
10234
10235 if (!Invalid) {
10236 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010237 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010238
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010239 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010240 if (Return.isInvalid())
10241 Invalid = true;
10242 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010243 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010244
10245 if (Trap.hasErrorOccurred()) {
10246 Diag(CurrentLocation, diag::note_member_synthesized_at)
10247 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10248 Invalid = true;
10249 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010250 }
10251 }
10252
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010253 // The exception specification is needed because we are defining the
10254 // function.
10255 ResolveExceptionSpec(CurrentLocation,
10256 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10257
Douglas Gregorb139cd52010-05-01 20:49:11 +000010258 if (Invalid) {
10259 CopyAssignOperator->setInvalidDecl();
10260 return;
10261 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010262
10263 StmtResult Body;
10264 {
10265 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010266 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010267 /*isStmtExpr=*/false);
10268 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10269 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010270 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010271
10272 if (ASTMutationListener *L = getASTMutationListener()) {
10273 L->CompletedImplicitDefinition(CopyAssignOperator);
10274 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010275}
10276
Sebastian Redl22653ba2011-08-30 19:58:05 +000010277Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010278Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10279 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010280
Richard Smithd3b5c9082012-07-27 04:22:15 +000010281 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010282 if (ClassDecl->isInvalidDecl())
10283 return ExceptSpec;
10284
10285 // C++0x [except.spec]p14:
10286 // An implicitly declared special member function (Clause 12) shall have an
10287 // exception-specification. [...]
10288
10289 // It is unspecified whether or not an implicit move assignment operator
10290 // attempts to deduplicate calls to assignment operators of virtual bases are
10291 // made. As such, this exception specification is effectively unspecified.
10292 // Based on a similar decision made for constness in C++0x, we're erring on
10293 // the side of assuming such calls to be made regardless of whether they
10294 // actually happen.
10295 // Note that a move constructor is not implicitly declared when there are
10296 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010297 for (const auto &Base : ClassDecl->bases()) {
10298 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 continue;
10300
10301 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010302 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010303 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010304 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010305 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010306 }
10307
Aaron Ballman445a9392014-03-13 16:15:17 +000010308 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010309 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010310 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010311 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010312 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010313 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010314 }
10315
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010316 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010317 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010318 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010319 if (CXXMethodDecl *MoveAssign =
10320 LookupMovingAssignment(FieldClassDecl,
10321 FieldType.getCVRQualifiers(),
10322 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010323 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010324 }
10325 }
10326
10327 return ExceptSpec;
10328}
10329
10330CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010331 assert(ClassDecl->needsImplicitMoveAssignment());
10332
Richard Smith8bf22e52012-11-29 01:34:07 +000010333 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10334 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010335 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010336
Sebastian Redl22653ba2011-08-30 19:58:05 +000010337 // Note: The following rules are largely analoguous to the move
10338 // constructor rules.
10339
Sebastian Redl22653ba2011-08-30 19:58:05 +000010340 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10341 QualType RetType = Context.getLValueReferenceType(ArgType);
10342 ArgType = Context.getRValueReferenceType(ArgType);
10343
Richard Smith99005e62013-05-07 03:19:20 +000010344 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10345 CXXMoveAssignment,
10346 false);
10347
Sebastian Redl22653ba2011-08-30 19:58:05 +000010348 // An implicitly-declared move assignment operator is an inline public
10349 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010350 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10351 SourceLocation ClassLoc = ClassDecl->getLocation();
10352 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010353 CXXMethodDecl *MoveAssignment =
10354 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010355 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010356 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010357 MoveAssignment->setAccess(AS_public);
10358 MoveAssignment->setDefaulted();
10359 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010360
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010361 if (getLangOpts().CUDA) {
10362 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10363 MoveAssignment,
10364 /* ConstRHS */ false,
10365 /* Diagnose */ false);
10366 }
10367
Richard Smithd3b5c9082012-07-27 04:22:15 +000010368 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010369 FunctionProtoType::ExtProtoInfo EPI =
10370 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010371 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010372
Sebastian Redl22653ba2011-08-30 19:58:05 +000010373 // Add the parameter to the operator.
10374 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010375 ClassLoc, ClassLoc,
10376 /*Id=*/nullptr, ArgType,
10377 /*TInfo=*/nullptr, SC_None,
10378 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010379 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010380
Richard Smith6b02d462012-12-08 08:32:28 +000010381 AddOverriddenMethods(ClassDecl, MoveAssignment);
10382
10383 MoveAssignment->setTrivial(
10384 ClassDecl->needsOverloadResolutionForMoveAssignment()
10385 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10386 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010387
Richard Smithd951a1d2012-02-18 02:02:13 +000010388 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010389 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10390 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010391 }
10392
Richard Smith6b02d462012-12-08 08:32:28 +000010393 // Note that we have added this copy-assignment operator.
10394 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10395
Sebastian Redl22653ba2011-08-30 19:58:05 +000010396 if (Scope *S = getScopeForContext(ClassDecl))
10397 PushOnScopeChains(MoveAssignment, S, false);
10398 ClassDecl->addDecl(MoveAssignment);
10399
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400 return MoveAssignment;
10401}
10402
Richard Smithb2504bd2013-11-04 04:26:14 +000010403/// Check if we're implicitly defining a move assignment operator for a class
10404/// with virtual bases. Such a move assignment might move-assign the virtual
10405/// base multiple times.
10406static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10407 SourceLocation CurrentLocation) {
10408 assert(!Class->isDependentContext() && "should not define dependent move");
10409
10410 // Only a virtual base could get implicitly move-assigned multiple times.
10411 // Only a non-trivial move assignment can observe this. We only want to
10412 // diagnose if we implicitly define an assignment operator that assigns
10413 // two base classes, both of which move-assign the same virtual base.
10414 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10415 Class->getNumBases() < 2)
10416 return;
10417
10418 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10419 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10420 VBaseMap VBases;
10421
Aaron Ballman574705e2014-03-13 15:41:46 +000010422 for (auto &BI : Class->bases()) {
10423 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010424 while (!Worklist.empty()) {
10425 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10426 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10427
10428 // If the base has no non-trivial move assignment operators,
10429 // we don't care about moves from it.
10430 if (!Base->hasNonTrivialMoveAssignment())
10431 continue;
10432
10433 // If there's nothing virtual here, skip it.
10434 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10435 continue;
10436
10437 // If we're not actually going to call a move assignment for this base,
10438 // or the selected move assignment is trivial, skip it.
10439 Sema::SpecialMemberOverloadResult *SMOR =
10440 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10441 /*ConstArg*/false, /*VolatileArg*/false,
10442 /*RValueThis*/true, /*ConstThis*/false,
10443 /*VolatileThis*/false);
10444 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10445 !SMOR->getMethod()->isMoveAssignmentOperator())
10446 continue;
10447
10448 if (BaseSpec->isVirtual()) {
10449 // We're going to move-assign this virtual base, and its move
10450 // assignment operator is not trivial. If this can happen for
10451 // multiple distinct direct bases of Class, diagnose it. (If it
10452 // only happens in one base, we'll diagnose it when synthesizing
10453 // that base class's move assignment operator.)
10454 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010455 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010456 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010457 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010458 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10459 << Class << Base;
10460 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10461 << (Base->getCanonicalDecl() ==
10462 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10463 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010464 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010465 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010466 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10467 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010468
10469 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010470 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010471 }
10472 } else {
10473 // Only walk over bases that have defaulted move assignment operators.
10474 // We assume that any user-provided move assignment operator handles
10475 // the multiple-moves-of-vbase case itself somehow.
10476 if (!SMOR->getMethod()->isDefaulted())
10477 continue;
10478
10479 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010480 for (auto &BI : Base->bases())
10481 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010482 }
10483 }
10484 }
10485}
10486
Sebastian Redl22653ba2011-08-30 19:58:05 +000010487void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10488 CXXMethodDecl *MoveAssignOperator) {
10489 assert((MoveAssignOperator->isDefaulted() &&
10490 MoveAssignOperator->isOverloadedOperator() &&
10491 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010492 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10493 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010494 "DefineImplicitMoveAssignment called for wrong function");
10495
10496 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10497
10498 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10499 MoveAssignOperator->setInvalidDecl();
10500 return;
10501 }
10502
Eli Friedman276dd182013-09-05 00:02:25 +000010503 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010504
Eli Friedmaneaf34142012-10-18 20:14:08 +000010505 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010506 DiagnosticErrorTrap Trap(Diags);
10507
10508 // C++0x [class.copy]p28:
10509 // The implicitly-defined or move assignment operator for a non-union class
10510 // X performs memberwise move assignment of its subobjects. The direct base
10511 // classes of X are assigned first, in the order of their declaration in the
10512 // base-specifier-list, and then the immediate non-static data members of X
10513 // are assigned, in the order in which they were declared in the class
10514 // definition.
10515
Richard Smithb2504bd2013-11-04 04:26:14 +000010516 // Issue a warning if our implicit move assignment operator will move
10517 // from a virtual base more than once.
10518 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010519
Sebastian Redl22653ba2011-08-30 19:58:05 +000010520 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010521 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010522
10523 // The parameter for the "other" object, which we are move from.
10524 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10525 QualType OtherRefType = Other->getType()->
10526 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010527 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010528 "Bad argument type of defaulted move assignment");
10529
10530 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010531 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10532 ? MoveAssignOperator->getLocEnd()
10533 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010534
Pavel Labath58934982013-08-30 08:52:28 +000010535 // Builds a reference to the "other" object.
10536 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010537 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010538 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010539
Pavel Labath58934982013-08-30 08:52:28 +000010540 // Builds the "this" pointer.
10541 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010542
Sebastian Redl22653ba2011-08-30 19:58:05 +000010543 // Assign base classes.
10544 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010545 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010546 // C++11 [class.copy]p28:
10547 // It is unspecified whether subobjects representing virtual base classes
10548 // are assigned more than once by the implicitly-defined copy assignment
10549 // operator.
10550 // FIXME: Do not assign to a vbase that will be assigned by some other base
10551 // class. For a move-assignment, this can result in the vbase being moved
10552 // multiple times.
10553
Sebastian Redl22653ba2011-08-30 19:58:05 +000010554 // Form the assignment:
10555 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010556 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010557 if (!BaseType->isRecordType()) {
10558 Invalid = true;
10559 continue;
10560 }
10561
10562 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010563 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010564
10565 // Construct the "from" expression, which is an implicit cast to the
10566 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010567 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010568
10569 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010570 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010571
10572 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010573 CastBuilder To(DerefThis,
10574 Context.getCVRQualifiedType(
10575 BaseType, MoveAssignOperator->getTypeQualifiers()),
10576 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010577
10578 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010579 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010580 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010581 /*CopyingBaseSubobject=*/true,
10582 /*Copying=*/false);
10583 if (Move.isInvalid()) {
10584 Diag(CurrentLocation, diag::note_member_synthesized_at)
10585 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10586 MoveAssignOperator->setInvalidDecl();
10587 return;
10588 }
10589
10590 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010591 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010592 }
10593
Sebastian Redl22653ba2011-08-30 19:58:05 +000010594 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010595 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010596 if (Field->isUnnamedBitfield())
10597 continue;
10598
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010599 if (Field->isInvalidDecl()) {
10600 Invalid = true;
10601 continue;
10602 }
10603
Sebastian Redl22653ba2011-08-30 19:58:05 +000010604 // Check for members of reference type; we can't move those.
10605 if (Field->getType()->isReferenceType()) {
10606 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10607 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10608 Diag(Field->getLocation(), diag::note_declared_at);
10609 Diag(CurrentLocation, diag::note_member_synthesized_at)
10610 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10611 Invalid = true;
10612 continue;
10613 }
10614
10615 // Check for members of const-qualified, non-class type.
10616 QualType BaseType = Context.getBaseElementType(Field->getType());
10617 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10618 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10619 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10620 Diag(Field->getLocation(), diag::note_declared_at);
10621 Diag(CurrentLocation, diag::note_member_synthesized_at)
10622 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10623 Invalid = true;
10624 continue;
10625 }
10626
10627 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010628 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10629 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010630
10631 QualType FieldType = Field->getType().getNonReferenceType();
10632 if (FieldType->isIncompleteArrayType()) {
10633 assert(ClassDecl->hasFlexibleArrayMember() &&
10634 "Incomplete array type is not valid");
10635 continue;
10636 }
10637
10638 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010639 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10640 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010641 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010642 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010643 MemberBuilder From(MoveOther, OtherRefType,
10644 /*IsArrow=*/false, MemberLookup);
10645 MemberBuilder To(This, getCurrentThisType(),
10646 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010647
Pavel Labath58934982013-08-30 08:52:28 +000010648 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010649 "Member reference with rvalue base must be rvalue except for reference "
10650 "members, which aren't allowed for move assignment.");
10651
Sebastian Redl22653ba2011-08-30 19:58:05 +000010652 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010653 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010654 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010655 /*CopyingBaseSubobject=*/false,
10656 /*Copying=*/false);
10657 if (Move.isInvalid()) {
10658 Diag(CurrentLocation, diag::note_member_synthesized_at)
10659 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10660 MoveAssignOperator->setInvalidDecl();
10661 return;
10662 }
Richard Smith11d19592012-11-12 23:33:00 +000010663
Sebastian Redl22653ba2011-08-30 19:58:05 +000010664 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010665 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010666 }
10667
10668 if (!Invalid) {
10669 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010670 ExprResult ThisObj =
10671 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10672
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010673 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010674 if (Return.isInvalid())
10675 Invalid = true;
10676 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010677 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010678
10679 if (Trap.hasErrorOccurred()) {
10680 Diag(CurrentLocation, diag::note_member_synthesized_at)
10681 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10682 Invalid = true;
10683 }
10684 }
10685 }
10686
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010687 // The exception specification is needed because we are defining the
10688 // function.
10689 ResolveExceptionSpec(CurrentLocation,
10690 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10691
Sebastian Redl22653ba2011-08-30 19:58:05 +000010692 if (Invalid) {
10693 MoveAssignOperator->setInvalidDecl();
10694 return;
10695 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010696
10697 StmtResult Body;
10698 {
10699 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010700 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010701 /*isStmtExpr=*/false);
10702 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10703 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010704 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010705
10706 if (ASTMutationListener *L = getASTMutationListener()) {
10707 L->CompletedImplicitDefinition(MoveAssignOperator);
10708 }
10709}
10710
Richard Smithd3b5c9082012-07-27 04:22:15 +000010711Sema::ImplicitExceptionSpecification
10712Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10713 CXXRecordDecl *ClassDecl = MD->getParent();
10714
10715 ImplicitExceptionSpecification ExceptSpec(*this);
10716 if (ClassDecl->isInvalidDecl())
10717 return ExceptSpec;
10718
10719 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010720 assert(T->getNumParams() >= 1 && "not a copy ctor");
10721 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010722
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010723 // C++ [except.spec]p14:
10724 // An implicitly declared special member function (Clause 12) shall have an
10725 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010726 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010727 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010728 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010729 continue;
10730
Douglas Gregora6d69502010-07-02 23:41:54 +000010731 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010732 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010733 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010734 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010735 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010736 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010737 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010738 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010739 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010740 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010741 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010742 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010743 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010744 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010745 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010746 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10747 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010748 LookupCopyingConstructor(FieldClassDecl,
10749 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010750 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010751 }
10752 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010753
Richard Smithd3b5c9082012-07-27 04:22:15 +000010754 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010755}
10756
10757CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10758 CXXRecordDecl *ClassDecl) {
10759 // C++ [class.copy]p4:
10760 // If the class definition does not explicitly declare a copy
10761 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010762 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010763
Richard Smith8bf22e52012-11-29 01:34:07 +000010764 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10765 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010766 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010767
Alexis Hunt913820d2011-05-13 06:10:58 +000010768 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10769 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010770 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010771 if (Const)
10772 ArgType = ArgType.withConst();
10773 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010774
Richard Smithb5800092012-06-10 05:43:50 +000010775 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10776 CXXCopyConstructor,
10777 Const);
10778
Douglas Gregor54be3392010-07-01 17:57:27 +000010779 DeclarationName Name
10780 = Context.DeclarationNames.getCXXConstructorName(
10781 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010782 SourceLocation ClassLoc = ClassDecl->getLocation();
10783 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010784
10785 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010786 // member of its class.
10787 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010788 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010789 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010790 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010791 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010792 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010793
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010794 if (getLangOpts().CUDA) {
10795 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10796 CopyConstructor,
10797 /* ConstRHS */ Const,
10798 /* Diagnose */ false);
10799 }
10800
Richard Smithd3b5c9082012-07-27 04:22:15 +000010801 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010802 FunctionProtoType::ExtProtoInfo EPI =
10803 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010804 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010805 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010806
Douglas Gregor54be3392010-07-01 17:57:27 +000010807 // Add the parameter to the constructor.
10808 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010809 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010810 /*IdentifierInfo=*/nullptr,
10811 ArgType, /*TInfo=*/nullptr,
10812 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010813 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010814
Richard Smith6b02d462012-12-08 08:32:28 +000010815 CopyConstructor->setTrivial(
10816 ClassDecl->needsOverloadResolutionForCopyConstructor()
10817 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10818 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010819
Richard Smith852265f2012-03-30 20:53:28 +000010820 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010821 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010822
Richard Smith6b02d462012-12-08 08:32:28 +000010823 // Note that we have declared this constructor.
10824 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10825
10826 if (Scope *S = getScopeForContext(ClassDecl))
10827 PushOnScopeChains(CopyConstructor, S, false);
10828 ClassDecl->addDecl(CopyConstructor);
10829
Douglas Gregor54be3392010-07-01 17:57:27 +000010830 return CopyConstructor;
10831}
10832
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010833void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010834 CXXConstructorDecl *CopyConstructor) {
10835 assert((CopyConstructor->isDefaulted() &&
10836 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010837 !CopyConstructor->doesThisDeclarationHaveABody() &&
10838 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010839 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010840
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010841 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010842 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010843
Richard Smithd577fbb2013-06-13 03:23:42 +000010844 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010845 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010846 // deprecated if the class has a user-declared copy assignment operator
10847 // or a user-declared destructor.
10848 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10849 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10850
Eli Friedmaneaf34142012-10-18 20:14:08 +000010851 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010852 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010853
David Blaikie3fc2f912013-01-17 05:26:25 +000010854 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010855 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010856 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010857 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010858 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010859 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010860 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10861 ? CopyConstructor->getLocEnd()
10862 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010863 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010864 CopyConstructor->setBody(
10865 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010866 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010867
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010868 // The exception specification is needed because we are defining the
10869 // function.
10870 ResolveExceptionSpec(CurrentLocation,
10871 CopyConstructor->getType()->castAs<FunctionProtoType>());
10872
Eli Friedman276dd182013-09-05 00:02:25 +000010873 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010874 MarkVTableUsed(CurrentLocation, ClassDecl);
10875
Sebastian Redlab238a72011-04-24 16:28:06 +000010876 if (ASTMutationListener *L = getASTMutationListener()) {
10877 L->CompletedImplicitDefinition(CopyConstructor);
10878 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010879}
10880
Sebastian Redl22653ba2011-08-30 19:58:05 +000010881Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010882Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10883 CXXRecordDecl *ClassDecl = MD->getParent();
10884
Sebastian Redl22653ba2011-08-30 19:58:05 +000010885 // C++ [except.spec]p14:
10886 // An implicitly declared special member function (Clause 12) shall have an
10887 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010888 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010889 if (ClassDecl->isInvalidDecl())
10890 return ExceptSpec;
10891
10892 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010893 for (const auto &B : ClassDecl->bases()) {
10894 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010895 continue;
10896
Aaron Ballman574705e2014-03-13 15:41:46 +000010897 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010898 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010899 CXXConstructorDecl *Constructor =
10900 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010901 // If this is a deleted function, add it anyway. This might be conformant
10902 // with the standard. This might not. I'm not sure. It might not matter.
10903 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010904 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010905 }
10906 }
10907
10908 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010909 for (const auto &B : ClassDecl->vbases()) {
10910 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010911 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010912 CXXConstructorDecl *Constructor =
10913 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010914 // If this is a deleted function, add it anyway. This might be conformant
10915 // with the standard. This might not. I'm not sure. It might not matter.
10916 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010917 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010918 }
10919 }
10920
10921 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010922 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010923 QualType FieldType = Context.getBaseElementType(F->getType());
10924 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10925 CXXConstructorDecl *Constructor =
10926 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010927 // If this is a deleted function, add it anyway. This might be conformant
10928 // with the standard. This might not. I'm not sure. It might not matter.
10929 // In particular, the problem is that this function never gets called. It
10930 // might just be ill-formed because this function attempts to refer to
10931 // a deleted function here.
10932 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010933 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010934 }
10935 }
10936
10937 return ExceptSpec;
10938}
10939
10940CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10941 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010942 assert(ClassDecl->needsImplicitMoveConstructor());
10943
Richard Smith8bf22e52012-11-29 01:34:07 +000010944 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10945 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010946 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010947
Sebastian Redl22653ba2011-08-30 19:58:05 +000010948 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10949 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010950
Richard Smithb5800092012-06-10 05:43:50 +000010951 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10952 CXXMoveConstructor,
10953 false);
10954
Sebastian Redl22653ba2011-08-30 19:58:05 +000010955 DeclarationName Name
10956 = Context.DeclarationNames.getCXXConstructorName(
10957 Context.getCanonicalType(ClassType));
10958 SourceLocation ClassLoc = ClassDecl->getLocation();
10959 DeclarationNameInfo NameInfo(Name, ClassLoc);
10960
Richard Smith99005e62013-05-07 03:19:20 +000010961 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010962 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010963 // member of its class.
10964 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010965 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010966 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010967 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010968 MoveConstructor->setAccess(AS_public);
10969 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010970
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010971 if (getLangOpts().CUDA) {
10972 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10973 MoveConstructor,
10974 /* ConstRHS */ false,
10975 /* Diagnose */ false);
10976 }
10977
Richard Smithd3b5c9082012-07-27 04:22:15 +000010978 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010979 FunctionProtoType::ExtProtoInfo EPI =
10980 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010981 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010982 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010983
Sebastian Redl22653ba2011-08-30 19:58:05 +000010984 // Add the parameter to the constructor.
10985 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10986 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010987 /*IdentifierInfo=*/nullptr,
10988 ArgType, /*TInfo=*/nullptr,
10989 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010990 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010991
Richard Smith6b02d462012-12-08 08:32:28 +000010992 MoveConstructor->setTrivial(
10993 ClassDecl->needsOverloadResolutionForMoveConstructor()
10994 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10995 : ClassDecl->hasTrivialMoveConstructor());
10996
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010997 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010998 ClassDecl->setImplicitMoveConstructorIsDeleted();
10999 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011000 }
11001
11002 // Note that we have declared this constructor.
11003 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11004
11005 if (Scope *S = getScopeForContext(ClassDecl))
11006 PushOnScopeChains(MoveConstructor, S, false);
11007 ClassDecl->addDecl(MoveConstructor);
11008
11009 return MoveConstructor;
11010}
11011
11012void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11013 CXXConstructorDecl *MoveConstructor) {
11014 assert((MoveConstructor->isDefaulted() &&
11015 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011016 !MoveConstructor->doesThisDeclarationHaveABody() &&
11017 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011018 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11019
11020 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11021 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11022
Eli Friedmaneaf34142012-10-18 20:14:08 +000011023 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011024 DiagnosticErrorTrap Trap(Diags);
11025
David Blaikie3fc2f912013-01-17 05:26:25 +000011026 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011027 Trap.hasErrorOccurred()) {
11028 Diag(CurrentLocation, diag::note_member_synthesized_at)
11029 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11030 MoveConstructor->setInvalidDecl();
11031 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011032 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11033 ? MoveConstructor->getLocEnd()
11034 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011035 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011036 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011037 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011038 }
11039
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011040 // The exception specification is needed because we are defining the
11041 // function.
11042 ResolveExceptionSpec(CurrentLocation,
11043 MoveConstructor->getType()->castAs<FunctionProtoType>());
11044
Eli Friedman276dd182013-09-05 00:02:25 +000011045 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011046 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011047
11048 if (ASTMutationListener *L = getASTMutationListener()) {
11049 L->CompletedImplicitDefinition(MoveConstructor);
11050 }
11051}
11052
Douglas Gregor74f7d502012-02-15 19:33:52 +000011053bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011054 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011055}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011056
11057void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011058 SourceLocation CurrentLocation,
11059 CXXConversionDecl *Conv) {
11060 CXXRecordDecl *Lambda = Conv->getParent();
11061 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11062 // If we are defining a specialization of a conversion to function-ptr
11063 // cache the deduced template arguments for this specialization
11064 // so that we can use them to retrieve the corresponding call-operator
11065 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011066 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11067
Faisal Vali571df122013-09-29 08:45:24 +000011068 // Retrieve the corresponding call-operator specialization.
11069 if (Lambda->isGenericLambda()) {
11070 assert(Conv->isFunctionTemplateSpecialization());
11071 FunctionTemplateDecl *CallOpTemplate =
11072 CallOp->getDescribedFunctionTemplate();
11073 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011074 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011075 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011076 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011077 InsertPos);
11078 assert(CallOpSpec &&
11079 "Conversion operator must have a corresponding call operator");
11080 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11081 }
11082 // Mark the call operator referenced (and add to pending instantiations
11083 // if necessary).
11084 // For both the conversion and static-invoker template specializations
11085 // we construct their body's in this function, so no need to add them
11086 // to the PendingInstantiations.
11087 MarkFunctionReferenced(CurrentLocation, CallOp);
11088
Eli Friedmaneaf34142012-10-18 20:14:08 +000011089 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011090 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011091
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011092 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011093 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11094 // ... and get the corresponding specialization for a generic lambda.
11095 if (Lambda->isGenericLambda()) {
11096 assert(DeducedTemplateArgs &&
11097 "Must have deduced template arguments from Conversion Operator");
11098 FunctionTemplateDecl *InvokeTemplate =
11099 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011100 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011101 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011102 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011103 InsertPos);
11104 assert(InvokeSpec &&
11105 "Must have a corresponding static invoker specialization");
11106 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11107 }
11108 // Construct the body of the conversion function { return __invoke; }.
11109 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011110 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011111 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011112 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011113 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11114 Conv->getLocation(),
11115 Conv->getLocation()));
11116
11117 Conv->markUsed(Context);
11118 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011119
Faisal Vali571df122013-09-29 08:45:24 +000011120 // Fill in the __invoke function with a dummy implementation. IR generation
11121 // will fill in the actual details.
11122 Invoker->markUsed(Context);
11123 Invoker->setReferenced();
11124 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11125
Douglas Gregord3b672c2012-02-16 01:06:16 +000011126 if (ASTMutationListener *L = getASTMutationListener()) {
11127 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011128 L->CompletedImplicitDefinition(Invoker);
11129 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011130}
11131
Faisal Vali571df122013-09-29 08:45:24 +000011132
11133
Douglas Gregord3b672c2012-02-16 01:06:16 +000011134void Sema::DefineImplicitLambdaToBlockPointerConversion(
11135 SourceLocation CurrentLocation,
11136 CXXConversionDecl *Conv)
11137{
Faisal Vali850da1a2013-09-29 17:08:32 +000011138 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011139
Eli Friedman276dd182013-09-05 00:02:25 +000011140 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011141
Eli Friedmaneaf34142012-10-18 20:14:08 +000011142 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011143 DiagnosticErrorTrap Trap(Diags);
11144
Douglas Gregored90df32012-02-22 05:02:47 +000011145 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011146 Expr *This = ActOnCXXThis(CurrentLocation).get();
11147 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011148
Eli Friedman98b01ed2012-03-01 04:01:32 +000011149 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11150 Conv->getLocation(),
11151 Conv, DerefThis);
11152
11153 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11154 // behavior. Note that only the general conversion function does this
11155 // (since it's unusable otherwise); in the case where we inline the
11156 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011157 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011158 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11159 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011160 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011161
11162 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011163 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011164 Conv->setInvalidDecl();
11165 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011166 }
Douglas Gregored90df32012-02-22 05:02:47 +000011167
Douglas Gregored90df32012-02-22 05:02:47 +000011168 // Create the return statement that returns the block from the conversion
11169 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011170 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011171 if (Return.isInvalid()) {
11172 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11173 Conv->setInvalidDecl();
11174 return;
11175 }
11176
11177 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011178 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011179 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011180 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011181 Conv->getLocation()));
11182
Douglas Gregored90df32012-02-22 05:02:47 +000011183 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011184 if (ASTMutationListener *L = getASTMutationListener()) {
11185 L->CompletedImplicitDefinition(Conv);
11186 }
11187}
11188
Douglas Gregord2f70072012-03-10 06:53:13 +000011189/// \brief Determine whether the given list arguments contains exactly one
11190/// "real" (non-default) argument.
11191static bool hasOneRealArgument(MultiExprArg Args) {
11192 switch (Args.size()) {
11193 case 0:
11194 return false;
11195
11196 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011197 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011198 return false;
11199
11200 // fall through
11201 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011202 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011203 }
11204
11205 return false;
11206}
11207
John McCalldadc5752010-08-24 06:29:42 +000011208ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011209Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011210 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011211 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011212 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011213 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011214 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011215 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011216 unsigned ConstructKind,
11217 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011218 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011219
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011220 // C++0x [class.copy]p34:
11221 // When certain criteria are met, an implementation is allowed to
11222 // omit the copy/move construction of a class object, even if the
11223 // copy/move constructor and/or destructor for the object have
11224 // side effects. [...]
11225 // - when a temporary class object that has not been bound to a
11226 // reference (12.2) would be copied/moved to a class object
11227 // with the same cv-unqualified type, the copy/move operation
11228 // can be omitted by constructing the temporary object
11229 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011230 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011231 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011232 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011233 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011234 }
Mike Stump11289f42009-09-09 15:08:12 +000011235
11236 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011237 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011238 IsListInitialization,
11239 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011240 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011241}
11242
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011243/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11244/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011245ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011246Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11247 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011248 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011249 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011250 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011251 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011252 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011253 unsigned ConstructKind,
11254 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011255 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011256 return CXXConstructExpr::Create(
11257 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011258 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11259 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011260 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11261 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011262}
11263
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011264ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11265 assert(Field->hasInClassInitializer());
11266
11267 // If we already have the in-class initializer nothing needs to be done.
11268 if (Field->getInClassInitializer())
11269 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11270
11271 // Maybe we haven't instantiated the in-class initializer. Go check the
11272 // pattern FieldDecl to see if it has one.
11273 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11274
11275 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11276 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11277 DeclContext::lookup_result Lookup =
11278 ClassPattern->lookup(Field->getDeclName());
11279 assert(Lookup.size() == 1);
11280 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11281 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11282 getTemplateInstantiationArgs(Field)))
11283 return ExprError();
11284 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11285 }
11286
11287 // DR1351:
11288 // If the brace-or-equal-initializer of a non-static data member
11289 // invokes a defaulted default constructor of its class or of an
11290 // enclosing class in a potentially evaluated subexpression, the
11291 // program is ill-formed.
11292 //
11293 // This resolution is unworkable: the exception specification of the
11294 // default constructor can be needed in an unevaluated context, in
11295 // particular, in the operand of a noexcept-expression, and we can be
11296 // unable to compute an exception specification for an enclosed class.
11297 //
11298 // Any attempt to resolve the exception specification of a defaulted default
11299 // constructor before the initializer is lexically complete will ultimately
11300 // come here at which point we can diagnose it.
11301 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11302 if (OutermostClass == ParentRD) {
11303 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11304 << ParentRD << Field;
11305 } else {
11306 Diag(Field->getLocEnd(),
11307 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11308 << ParentRD << OutermostClass << Field;
11309 }
11310
11311 return ExprError();
11312}
11313
John McCall03c48482010-02-02 09:10:11 +000011314void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011315 if (VD->isInvalidDecl()) return;
11316
John McCall03c48482010-02-02 09:10:11 +000011317 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011318 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011319 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011320 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011321
Chandler Carruth86d17d32011-03-27 21:26:48 +000011322 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011323 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011324 CheckDestructorAccess(VD->getLocation(), Destructor,
11325 PDiag(diag::err_access_dtor_var)
11326 << VD->getDeclName()
11327 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011328 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011329
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011330 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011331 if (!VD->hasGlobalStorage()) return;
11332
11333 // Emit warning for non-trivial dtor in global scope (a real global,
11334 // class-static, function-static).
11335 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11336
11337 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011338 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011339 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011340}
11341
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011342/// \brief Given a constructor and the set of arguments provided for the
11343/// constructor, convert the arguments and add any required default arguments
11344/// to form a proper call to this constructor.
11345///
11346/// \returns true if an error occurred, false otherwise.
11347bool
11348Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11349 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011350 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011351 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011352 bool AllowExplicit,
11353 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011354 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11355 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011356 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011357
11358 const FunctionProtoType *Proto
11359 = Constructor->getType()->getAs<FunctionProtoType>();
11360 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011361 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011362
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011363 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011364 if (NumArgs < NumParams)
11365 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011366 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011367 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011368
11369 VariadicCallType CallType =
11370 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011371 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011372 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011373 Proto, 0,
11374 llvm::makeArrayRef(Args, NumArgs),
11375 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011376 CallType, AllowExplicit,
11377 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011378 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011379
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011380 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011381
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011382 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011383 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011384 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011385
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011386 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011387}
11388
Anders Carlssone363c8e2009-12-12 00:32:00 +000011389static inline bool
11390CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11391 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011392 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011393 if (isa<NamespaceDecl>(DC)) {
11394 return SemaRef.Diag(FnDecl->getLocation(),
11395 diag::err_operator_new_delete_declared_in_namespace)
11396 << FnDecl->getDeclName();
11397 }
11398
11399 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011400 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011401 return SemaRef.Diag(FnDecl->getLocation(),
11402 diag::err_operator_new_delete_declared_static)
11403 << FnDecl->getDeclName();
11404 }
11405
Anders Carlsson60659a82009-12-12 02:43:16 +000011406 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011407}
11408
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011409static inline bool
11410CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11411 CanQualType ExpectedResultType,
11412 CanQualType ExpectedFirstParamType,
11413 unsigned DependentParamTypeDiag,
11414 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011415 QualType ResultType =
11416 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011417
11418 // Check that the result type is not dependent.
11419 if (ResultType->isDependentType())
11420 return SemaRef.Diag(FnDecl->getLocation(),
11421 diag::err_operator_new_delete_dependent_result_type)
11422 << FnDecl->getDeclName() << ExpectedResultType;
11423
11424 // Check that the result type is what we expect.
11425 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11426 return SemaRef.Diag(FnDecl->getLocation(),
11427 diag::err_operator_new_delete_invalid_result_type)
11428 << FnDecl->getDeclName() << ExpectedResultType;
11429
11430 // A function template must have at least 2 parameters.
11431 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11432 return SemaRef.Diag(FnDecl->getLocation(),
11433 diag::err_operator_new_delete_template_too_few_parameters)
11434 << FnDecl->getDeclName();
11435
11436 // The function decl must have at least 1 parameter.
11437 if (FnDecl->getNumParams() == 0)
11438 return SemaRef.Diag(FnDecl->getLocation(),
11439 diag::err_operator_new_delete_too_few_parameters)
11440 << FnDecl->getDeclName();
11441
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011442 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011443 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11444 if (FirstParamType->isDependentType())
11445 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11446 << FnDecl->getDeclName() << ExpectedFirstParamType;
11447
11448 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011449 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011450 ExpectedFirstParamType)
11451 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11452 << FnDecl->getDeclName() << ExpectedFirstParamType;
11453
11454 return false;
11455}
11456
Anders Carlsson12308f42009-12-11 23:23:22 +000011457static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011458CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011459 // C++ [basic.stc.dynamic.allocation]p1:
11460 // A program is ill-formed if an allocation function is declared in a
11461 // namespace scope other than global scope or declared static in global
11462 // scope.
11463 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11464 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011465
11466 CanQualType SizeTy =
11467 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11468
11469 // C++ [basic.stc.dynamic.allocation]p1:
11470 // The return type shall be void*. The first parameter shall have type
11471 // std::size_t.
11472 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11473 SizeTy,
11474 diag::err_operator_new_dependent_param_type,
11475 diag::err_operator_new_param_type))
11476 return true;
11477
11478 // C++ [basic.stc.dynamic.allocation]p1:
11479 // The first parameter shall not have an associated default argument.
11480 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011481 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011482 diag::err_operator_new_default_arg)
11483 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11484
11485 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011486}
11487
11488static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011489CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011490 // C++ [basic.stc.dynamic.deallocation]p1:
11491 // A program is ill-formed if deallocation functions are declared in a
11492 // namespace scope other than global scope or declared static in global
11493 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011494 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11495 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011496
11497 // C++ [basic.stc.dynamic.deallocation]p2:
11498 // Each deallocation function shall return void and its first parameter
11499 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011500 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11501 SemaRef.Context.VoidPtrTy,
11502 diag::err_operator_delete_dependent_param_type,
11503 diag::err_operator_delete_param_type))
11504 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011505
Anders Carlsson12308f42009-12-11 23:23:22 +000011506 return false;
11507}
11508
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011509/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11510/// of this overloaded operator is well-formed. If so, returns false;
11511/// otherwise, emits appropriate diagnostics and returns true.
11512bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011513 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011514 "Expected an overloaded operator declaration");
11515
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011516 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11517
Mike Stump11289f42009-09-09 15:08:12 +000011518 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011519 // The allocation and deallocation functions, operator new,
11520 // operator new[], operator delete and operator delete[], are
11521 // described completely in 3.7.3. The attributes and restrictions
11522 // found in the rest of this subclause do not apply to them unless
11523 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011524 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011525 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011526
Anders Carlsson22f443f2009-12-12 00:26:23 +000011527 if (Op == OO_New || Op == OO_Array_New)
11528 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011529
11530 // C++ [over.oper]p6:
11531 // An operator function shall either be a non-static member
11532 // function or be a non-member function and have at least one
11533 // parameter whose type is a class, a reference to a class, an
11534 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011535 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11536 if (MethodDecl->isStatic())
11537 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011538 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011539 } else {
11540 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011541 for (auto Param : FnDecl->params()) {
11542 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011543 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11544 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011545 ClassOrEnumParam = true;
11546 break;
11547 }
11548 }
11549
Douglas Gregord69246b2008-11-17 16:14:12 +000011550 if (!ClassOrEnumParam)
11551 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011552 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011553 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011554 }
11555
11556 // C++ [over.oper]p8:
11557 // An operator function cannot have default arguments (8.3.6),
11558 // except where explicitly stated below.
11559 //
Mike Stump11289f42009-09-09 15:08:12 +000011560 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011561 // (C++ [over.call]p1).
11562 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011563 for (auto Param : FnDecl->params()) {
11564 if (Param->hasDefaultArg())
11565 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011566 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011567 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011568 }
11569 }
11570
Douglas Gregor6cf08062008-11-10 13:38:07 +000011571 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11572 { false, false, false }
11573#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11574 , { Unary, Binary, MemberOnly }
11575#include "clang/Basic/OperatorKinds.def"
11576 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011577
Douglas Gregor6cf08062008-11-10 13:38:07 +000011578 bool CanBeUnaryOperator = OperatorUses[Op][0];
11579 bool CanBeBinaryOperator = OperatorUses[Op][1];
11580 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011581
11582 // C++ [over.oper]p8:
11583 // [...] Operator functions cannot have more or fewer parameters
11584 // than the number required for the corresponding operator, as
11585 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011586 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011587 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011588 if (Op != OO_Call &&
11589 ((NumParams == 1 && !CanBeUnaryOperator) ||
11590 (NumParams == 2 && !CanBeBinaryOperator) ||
11591 (NumParams < 1) || (NumParams > 2))) {
11592 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011593 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011594 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011595 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011596 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011597 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011598 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011599 assert(CanBeBinaryOperator &&
11600 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011601 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011602 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011603
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011604 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011605 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011606 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011607
Douglas Gregord69246b2008-11-17 16:14:12 +000011608 // Overloaded operators other than operator() cannot be variadic.
11609 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011610 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011611 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011612 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011613 }
11614
11615 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011616 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11617 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011618 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011619 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011620 }
11621
11622 // C++ [over.inc]p1:
11623 // The user-defined function called operator++ implements the
11624 // prefix and postfix ++ operator. If this function is a member
11625 // function with no parameters, or a non-member function with one
11626 // parameter of class or enumeration type, it defines the prefix
11627 // increment operator ++ for objects of that type. If the function
11628 // is a member function with one parameter (which shall be of type
11629 // int) or a non-member function with two parameters (the second
11630 // of which shall be of type int), it defines the postfix
11631 // increment operator ++ for objects of that type.
11632 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11633 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011634 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011635
Richard Smith538b52a2014-01-30 22:24:05 +000011636 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11637 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011638 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011639 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011640 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011641 }
11642
Douglas Gregord69246b2008-11-17 16:14:12 +000011643 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011644}
Chris Lattner3b024a32008-12-17 07:09:26 +000011645
Alexis Huntc88db062010-01-13 09:01:02 +000011646/// CheckLiteralOperatorDeclaration - Check whether the declaration
11647/// of this literal operator function is well-formed. If so, returns
11648/// false; otherwise, emits appropriate diagnostics and returns true.
11649bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011650 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011651 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11652 << FnDecl->getDeclName();
11653 return true;
11654 }
11655
Richard Smith72eebee2012-03-04 09:41:16 +000011656 if (FnDecl->isExternC()) {
11657 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11658 return true;
11659 }
11660
Alexis Huntc88db062010-01-13 09:01:02 +000011661 bool Valid = false;
11662
Richard Smithbcc22fc2012-03-09 08:00:36 +000011663 // This might be the definition of a literal operator template.
11664 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11665 // This might be a specialization of a literal operator template.
11666 if (!TpDecl)
11667 TpDecl = FnDecl->getPrimaryTemplate();
11668
Richard Smithb8b41d32013-10-07 19:57:58 +000011669 // template <char...> type operator "" name() and
11670 // template <class T, T...> type operator "" name() are the only valid
11671 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011672 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011673 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011674 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011675 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11676 if (Params->size() == 1) {
11677 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011678 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011679
Alexis Hunt7dd26172010-04-07 23:11:06 +000011680 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011681 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11682 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11683 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011684 } else if (Params->size() == 2) {
11685 TemplateTypeParmDecl *PmType =
11686 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11687 NonTypeTemplateParmDecl *PmArgs =
11688 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11689
11690 // The second template parameter must be a parameter pack with the
11691 // first template parameter as its type.
11692 if (PmType && PmArgs &&
11693 !PmType->isTemplateParameterPack() &&
11694 PmArgs->isTemplateParameterPack()) {
11695 const TemplateTypeParmType *TArgs =
11696 PmArgs->getType()->getAs<TemplateTypeParmType>();
11697 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11698 TArgs->getIndex() == PmType->getIndex()) {
11699 Valid = true;
11700 if (ActiveTemplateInstantiations.empty())
11701 Diag(FnDecl->getLocation(),
11702 diag::ext_string_literal_operator_template);
11703 }
11704 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011705 }
11706 }
Richard Smith72eebee2012-03-04 09:41:16 +000011707 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011708 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011709 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11710
Richard Smith72eebee2012-03-04 09:41:16 +000011711 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011712
Alexis Hunt079a6f72010-04-07 22:57:35 +000011713 // unsigned long long int, long double, and any character type are allowed
11714 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011715 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11716 Context.hasSameType(T, Context.LongDoubleTy) ||
11717 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011718 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011719 Context.hasSameType(T, Context.Char16Ty) ||
11720 Context.hasSameType(T, Context.Char32Ty)) {
11721 if (++Param == FnDecl->param_end())
11722 Valid = true;
11723 goto FinishedParams;
11724 }
11725
Alexis Hunt079a6f72010-04-07 22:57:35 +000011726 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011727 const PointerType *PT = T->getAs<PointerType>();
11728 if (!PT)
11729 goto FinishedParams;
11730 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011731 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011732 goto FinishedParams;
11733 T = T.getUnqualifiedType();
11734
11735 // Move on to the second parameter;
11736 ++Param;
11737
11738 // If there is no second parameter, the first must be a const char *
11739 if (Param == FnDecl->param_end()) {
11740 if (Context.hasSameType(T, Context.CharTy))
11741 Valid = true;
11742 goto FinishedParams;
11743 }
11744
11745 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11746 // are allowed as the first parameter to a two-parameter function
11747 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011748 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011749 Context.hasSameType(T, Context.Char16Ty) ||
11750 Context.hasSameType(T, Context.Char32Ty)))
11751 goto FinishedParams;
11752
11753 // The second and final parameter must be an std::size_t
11754 T = (*Param)->getType().getUnqualifiedType();
11755 if (Context.hasSameType(T, Context.getSizeType()) &&
11756 ++Param == FnDecl->param_end())
11757 Valid = true;
11758 }
11759
11760 // FIXME: This diagnostic is absolutely terrible.
11761FinishedParams:
11762 if (!Valid) {
11763 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11764 << FnDecl->getDeclName();
11765 return true;
11766 }
11767
Richard Smith768cecc2012-03-09 08:16:22 +000011768 // A parameter-declaration-clause containing a default argument is not
11769 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011770 for (auto Param : FnDecl->params()) {
11771 if (Param->hasDefaultArg()) {
11772 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011773 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011774 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011775 break;
11776 }
11777 }
11778
Richard Smith0df56f42012-03-08 02:39:21 +000011779 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011780 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11781 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011782 // C++11 [usrlit.suffix]p1:
11783 // Literal suffix identifiers that do not start with an underscore
11784 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011785 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11786 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011787 }
Richard Smith0df56f42012-03-08 02:39:21 +000011788
Alexis Huntc88db062010-01-13 09:01:02 +000011789 return false;
11790}
11791
Douglas Gregor07665a62009-01-05 19:45:36 +000011792/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11793/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011794/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11795/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011796/// the '{' brace. Otherwise, this linkage specification does not
11797/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011798Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011799 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011800 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011801 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11802 if (!Lit->isAscii()) {
11803 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11804 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011805 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011806 }
11807
11808 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011809 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011810 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011811 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011812 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011813 Language = LinkageSpecDecl::lang_cxx;
11814 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011815 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11816 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011817 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011818 }
Mike Stump11289f42009-09-09 15:08:12 +000011819
Chris Lattner438e5012008-12-17 07:13:27 +000011820 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011821
Richard Smith4ee696d2014-02-17 23:25:27 +000011822 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11823 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011824 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011825 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011826 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011827 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011828}
11829
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011830/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011831/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11832/// valid, it's the position of the closing '}' brace in a linkage
11833/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011834Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011835 Decl *LinkageSpec,
11836 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011837 if (RBraceLoc.isValid()) {
11838 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11839 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011840 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011841 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011842 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011843}
11844
Michael Han84324352013-02-22 17:15:32 +000011845Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11846 AttributeList *AttrList,
11847 SourceLocation SemiLoc) {
11848 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11849 // Attribute declarations appertain to empty declaration so we handle
11850 // them here.
11851 if (AttrList)
11852 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011853
Michael Han84324352013-02-22 17:15:32 +000011854 CurContext->addDecl(ED);
11855 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011856}
11857
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011858/// \brief Perform semantic analysis for the variable declaration that
11859/// occurs within a C++ catch clause, returning the newly-created
11860/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011861VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011862 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011863 SourceLocation StartLoc,
11864 SourceLocation Loc,
11865 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011866 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011867 QualType ExDeclType = TInfo->getType();
11868
Sebastian Redl54c04d42008-12-22 19:15:10 +000011869 // Arrays and functions decay.
11870 if (ExDeclType->isArrayType())
11871 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11872 else if (ExDeclType->isFunctionType())
11873 ExDeclType = Context.getPointerType(ExDeclType);
11874
11875 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11876 // The exception-declaration shall not denote a pointer or reference to an
11877 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011878 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011879 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011880 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011881 Invalid = true;
11882 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011883
Sebastian Redl54c04d42008-12-22 19:15:10 +000011884 QualType BaseType = ExDeclType;
11885 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011886 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011887 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011888 BaseType = Ptr->getPointeeType();
11889 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011890 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011891 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011892 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011893 BaseType = Ref->getPointeeType();
11894 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011895 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011896 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011897 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011898 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011899 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011900
Mike Stump11289f42009-09-09 15:08:12 +000011901 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011902 RequireNonAbstractType(Loc, ExDeclType,
11903 diag::err_abstract_type_in_decl,
11904 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011905 Invalid = true;
11906
John McCall2ca705e2010-07-24 00:37:23 +000011907 // Only the non-fragile NeXT runtime currently supports C++ catches
11908 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011909 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011910 QualType T = ExDeclType;
11911 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11912 T = RT->getPointeeType();
11913
11914 if (T->isObjCObjectType()) {
11915 Diag(Loc, diag::err_objc_object_catch);
11916 Invalid = true;
11917 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011918 // FIXME: should this be a test for macosx-fragile specifically?
11919 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011920 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011921 }
11922 }
11923
Abramo Bagnaradff19302011-03-08 08:55:46 +000011924 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011925 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011926 ExDecl->setExceptionVariable(true);
11927
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011928 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011929 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011930 Invalid = true;
11931
Douglas Gregor750734c2011-07-06 18:14:43 +000011932 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011933 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011934 // Insulate this from anything else we might currently be parsing.
11935 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11936
Douglas Gregor6de584c2010-03-05 23:38:39 +000011937 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011938 // The object declared in an exception-declaration or, if the
11939 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011940 // copy-initialized (8.5) from the exception object. [...]
11941 // The object is destroyed when the handler exits, after the destruction
11942 // of any automatic objects initialized within the handler.
11943 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011944 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011945 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011946 QualType initType = ExDeclType;
11947
11948 InitializedEntity entity =
11949 InitializedEntity::InitializeVariable(ExDecl);
11950 InitializationKind initKind =
11951 InitializationKind::CreateCopy(Loc, SourceLocation());
11952
11953 Expr *opaqueValue =
11954 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011955 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11956 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011957 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011958 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011959 else {
11960 // If the constructor used was non-trivial, set this as the
11961 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011962 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011963 if (!construct->getConstructor()->isTrivial()) {
11964 Expr *init = MaybeCreateExprWithCleanups(construct);
11965 ExDecl->setInit(init);
11966 }
11967
11968 // And make sure it's destructable.
11969 FinalizeVarWithDestructor(ExDecl, recordType);
11970 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011971 }
11972 }
11973
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011974 if (Invalid)
11975 ExDecl->setInvalidDecl();
11976
11977 return ExDecl;
11978}
11979
11980/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11981/// handler.
John McCall48871652010-08-21 09:40:31 +000011982Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011983 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011984 bool Invalid = D.isInvalidType();
11985
11986 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011987 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11988 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011989 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11990 D.getIdentifierLoc());
11991 Invalid = true;
11992 }
11993
Sebastian Redl54c04d42008-12-22 19:15:10 +000011994 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011995 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011996 LookupOrdinaryName,
11997 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011998 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011999 // it contains any previous declaration, except for function parameters in
12000 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012001 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012002 if (isDeclInScope(PrevDecl, CurContext, S)) {
12003 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12004 << D.getIdentifier();
12005 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12006 Invalid = true;
12007 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012008 // Maybe we will complain about the shadowed template parameter.
12009 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012010 }
12011
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012012 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012013 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12014 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012015 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012016 }
12017
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012018 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012019 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012020 D.getIdentifierLoc(),
12021 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012022 if (Invalid)
12023 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012024
Sebastian Redl54c04d42008-12-22 19:15:10 +000012025 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012026 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012027 PushOnScopeChains(ExDecl, S);
12028 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012029 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012030
Douglas Gregor758a8692009-06-17 21:51:59 +000012031 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012032 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012033}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012034
Abramo Bagnaraea947882011-03-08 16:41:52 +000012035Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012036 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012037 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012038 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012039 StringLiteral *AssertMessage =
12040 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012041
Richard Smithded9c2e2012-07-11 22:37:56 +000012042 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012043 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012044
12045 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12046 AssertMessage, RParenLoc, false);
12047}
12048
12049Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12050 Expr *AssertExpr,
12051 StringLiteral *AssertMessage,
12052 SourceLocation RParenLoc,
12053 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012054 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012055 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12056 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012057 // In a static_assert-declaration, the constant-expression shall be a
12058 // constant expression that can be contextually converted to bool.
12059 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12060 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012061 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012062
Richard Smith902ca212011-12-14 23:32:26 +000012063 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012064 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012065 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012066 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012067 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012068
Richard Smithded9c2e2012-07-11 22:37:56 +000012069 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012070 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012071 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012072 if (AssertMessage)
12073 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012074 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012075 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012076 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012077 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012078 }
Mike Stump11289f42009-09-09 15:08:12 +000012079
Abramo Bagnaraea947882011-03-08 16:41:52 +000012080 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012081 AssertExpr, AssertMessage, RParenLoc,
12082 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012083
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012084 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012085 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012086}
Sebastian Redlf769df52009-03-24 22:27:57 +000012087
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012088/// \brief Perform semantic analysis of the given friend type declaration.
12089///
12090/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012091FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012092 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012093 TypeSourceInfo *TSInfo) {
12094 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12095
12096 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012097 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012098
Richard Smithc8239732011-10-18 21:39:00 +000012099 // C++03 [class.friend]p2:
12100 // An elaborated-type-specifier shall be used in a friend declaration
12101 // for a class.*
12102 //
12103 // * The class-key of the elaborated-type-specifier is required.
12104 if (!ActiveTemplateInstantiations.empty()) {
12105 // Do not complain about the form of friend template types during
12106 // template instantiation; we will already have complained when the
12107 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012108 } else {
12109 if (!T->isElaboratedTypeSpecifier()) {
12110 // If we evaluated the type to a record type, suggest putting
12111 // a tag in front.
12112 if (const RecordType *RT = T->getAs<RecordType>()) {
12113 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012114
12115 SmallString<16> InsertionText(" ");
12116 InsertionText += RD->getKindName();
12117
Nick Lewycky36722d22013-02-06 05:59:33 +000012118 Diag(TypeRange.getBegin(),
12119 getLangOpts().CPlusPlus11 ?
12120 diag::warn_cxx98_compat_unelaborated_friend_type :
12121 diag::ext_unelaborated_friend_type)
12122 << (unsigned) RD->getTagKind()
12123 << T
12124 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12125 InsertionText);
12126 } else {
12127 Diag(FriendLoc,
12128 getLangOpts().CPlusPlus11 ?
12129 diag::warn_cxx98_compat_nonclass_type_friend :
12130 diag::ext_nonclass_type_friend)
12131 << T
12132 << TypeRange;
12133 }
12134 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012135 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012136 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012137 diag::warn_cxx98_compat_enum_friend :
12138 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012139 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012140 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012141 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012142
Nick Lewycky36722d22013-02-06 05:59:33 +000012143 // C++11 [class.friend]p3:
12144 // A friend declaration that does not declare a function shall have one
12145 // of the following forms:
12146 // friend elaborated-type-specifier ;
12147 // friend simple-type-specifier ;
12148 // friend typename-specifier ;
12149 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12150 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12151 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012152
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012153 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012154 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012155 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012156 return FriendDecl::Create(Context, CurContext,
12157 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12158 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012159}
12160
John McCallace48cd2010-10-19 01:40:49 +000012161/// Handle a friend tag declaration where the scope specifier was
12162/// templated.
12163Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12164 unsigned TagSpec, SourceLocation TagLoc,
12165 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012166 IdentifierInfo *Name,
12167 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012168 AttributeList *Attr,
12169 MultiTemplateParamsArg TempParamLists) {
12170 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12171
12172 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012173 bool Invalid = false;
12174
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012175 if (TemplateParameterList *TemplateParams =
12176 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012177 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012178 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012179 if (TemplateParams->size() > 0) {
12180 // This is a declaration of a class template.
12181 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012182 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012183
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012184 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12185 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012186 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012187 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012188 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012189 } else {
12190 // The "template<>" header is extraneous.
12191 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12192 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12193 isExplicitSpecialization = true;
12194 }
12195 }
12196
Craig Topperc3ec1492014-05-26 06:22:03 +000012197 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012198
John McCallace48cd2010-10-19 01:40:49 +000012199 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012200 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012201 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012202 isAllExplicitSpecializations = false;
12203 break;
12204 }
12205 }
12206
12207 // FIXME: don't ignore attributes.
12208
12209 // If it's explicit specializations all the way down, just forget
12210 // about the template header and build an appropriate non-templated
12211 // friend. TODO: for source fidelity, remember the headers.
12212 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012213 if (SS.isEmpty()) {
12214 bool Owned = false;
12215 bool IsDependent = false;
12216 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012217 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012218 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012219 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012220 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012221 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012222 /*UnderlyingType=*/TypeResult(),
12223 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012224 }
Richard Smith649c7b062014-01-08 00:56:48 +000012225
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012226 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012227 ElaboratedTypeKeyword Keyword
12228 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012229 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012230 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012231 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012232 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012233
12234 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12235 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012236 DependentNameTypeLoc TL =
12237 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012238 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012239 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012240 TL.setNameLoc(NameLoc);
12241 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012242 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012243 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012244 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012245 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012246 }
12247
12248 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012249 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012250 Friend->setAccess(AS_public);
12251 CurContext->addDecl(Friend);
12252 return Friend;
12253 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012254
12255 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12256
12257
John McCallace48cd2010-10-19 01:40:49 +000012258
12259 // Handle the case of a templated-scope friend class. e.g.
12260 // template <class T> class A<T>::B;
12261 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012262 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12263 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012264 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12265 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12266 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012267 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012268 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012269 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012270 TL.setNameLoc(NameLoc);
12271
12272 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012273 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012274 Friend->setAccess(AS_public);
12275 Friend->setUnsupportedFriend(true);
12276 CurContext->addDecl(Friend);
12277 return Friend;
12278}
12279
12280
John McCall11083da2009-09-16 22:47:08 +000012281/// Handle a friend type declaration. This works in tandem with
12282/// ActOnTag.
12283///
12284/// Notes on friend class templates:
12285///
12286/// We generally treat friend class declarations as if they were
12287/// declaring a class. So, for example, the elaborated type specifier
12288/// in a friend declaration is required to obey the restrictions of a
12289/// class-head (i.e. no typedefs in the scope chain), template
12290/// parameters are required to match up with simple template-ids, &c.
12291/// However, unlike when declaring a template specialization, it's
12292/// okay to refer to a template specialization without an empty
12293/// template parameter declaration, e.g.
12294/// friend class A<T>::B<unsigned>;
12295/// We permit this as a special case; if there are any template
12296/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012297/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012298Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012299 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012300 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012301
12302 assert(DS.isFriendSpecified());
12303 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12304
John McCall11083da2009-09-16 22:47:08 +000012305 // Try to convert the decl specifier to a type. This works for
12306 // friend templates because ActOnTag never produces a ClassTemplateDecl
12307 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012308 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012309 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12310 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012311 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012312 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012313
Douglas Gregor6c110f32010-12-16 01:14:37 +000012314 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012315 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012316
John McCall11083da2009-09-16 22:47:08 +000012317 // This is definitely an error in C++98. It's probably meant to
12318 // be forbidden in C++0x, too, but the specification is just
12319 // poorly written.
12320 //
12321 // The problem is with declarations like the following:
12322 // template <T> friend A<T>::foo;
12323 // where deciding whether a class C is a friend or not now hinges
12324 // on whether there exists an instantiation of A that causes
12325 // 'foo' to equal C. There are restrictions on class-heads
12326 // (which we declare (by fiat) elaborated friend declarations to
12327 // be) that makes this tractable.
12328 //
12329 // FIXME: handle "template <> friend class A<T>;", which
12330 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012331 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012332 Diag(Loc, diag::err_tagless_friend_type_template)
12333 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012334 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012335 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012336
John McCallaa74a0c2009-08-28 07:59:38 +000012337 // C++98 [class.friend]p1: A friend of a class is a function
12338 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012339 // This is fixed in DR77, which just barely didn't make the C++03
12340 // deadline. It's also a very silly restriction that seriously
12341 // affects inner classes and which nobody else seems to implement;
12342 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012343 //
12344 // But note that we could warn about it: it's always useless to
12345 // friend one of your own members (it's not, however, worthless to
12346 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012347
John McCall11083da2009-09-16 22:47:08 +000012348 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012349 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012350 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012351 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012352 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012353 TSI,
John McCall11083da2009-09-16 22:47:08 +000012354 DS.getFriendSpecLoc());
12355 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012356 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012357
12358 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012359 return nullptr;
12360
John McCall11083da2009-09-16 22:47:08 +000012361 D->setAccess(AS_public);
12362 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012363
John McCall48871652010-08-21 09:40:31 +000012364 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012365}
12366
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012367NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12368 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012369 const DeclSpec &DS = D.getDeclSpec();
12370
12371 assert(DS.isFriendSpecified());
12372 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12373
12374 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012375 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012376
12377 // C++ [class.friend]p1
12378 // A friend of a class is a function or class....
12379 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012380 // It *doesn't* see through dependent types, which is correct
12381 // according to [temp.arg.type]p3:
12382 // If a declaration acquires a function type through a
12383 // type dependent on a template-parameter and this causes
12384 // a declaration that does not use the syntactic form of a
12385 // function declarator to have a function type, the program
12386 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012387 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012388 Diag(Loc, diag::err_unexpected_friend);
12389
12390 // It might be worthwhile to try to recover by creating an
12391 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012392 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012393 }
12394
12395 // C++ [namespace.memdef]p3
12396 // - If a friend declaration in a non-local class first declares a
12397 // class or function, the friend class or function is a member
12398 // of the innermost enclosing namespace.
12399 // - The name of the friend is not found by simple name lookup
12400 // until a matching declaration is provided in that namespace
12401 // scope (either before or after the class declaration granting
12402 // friendship).
12403 // - If a friend function is called, its name may be found by the
12404 // name lookup that considers functions from namespaces and
12405 // classes associated with the types of the function arguments.
12406 // - When looking for a prior declaration of a class or a function
12407 // declared as a friend, scopes outside the innermost enclosing
12408 // namespace scope are not considered.
12409
John McCallde3fd222010-10-12 23:13:28 +000012410 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012411 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12412 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012413 assert(Name);
12414
Douglas Gregor6c110f32010-12-16 01:14:37 +000012415 // Check for unexpanded parameter packs.
12416 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12417 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12418 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012419 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012420
John McCall07e91c02009-08-06 02:15:43 +000012421 // The context we found the declaration in, or in which we should
12422 // create the declaration.
12423 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012424 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012425 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012426 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012427
Richard Smith114394f2013-08-09 04:35:01 +000012428 // There are five cases here.
12429 // - There's no scope specifier and we're in a local class. Only look
12430 // for functions declared in the immediately-enclosing block scope.
12431 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012432 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012433 if ((SS.isInvalid() || !SS.isSet()) &&
12434 (FunctionContainingLocalClass =
12435 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12436 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012437 // If a friend declaration appears in a local class and the name
12438 // specified is an unqualified name, a prior declaration is
12439 // looked up without considering scopes that are outside the
12440 // innermost enclosing non-class scope. For a friend function
12441 // declaration, if there is no prior declaration, the program is
12442 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012443
12444 // Find the innermost enclosing non-class scope. This is the block
12445 // scope containing the local class definition (or for a nested class,
12446 // the outer local class).
12447 DCScope = S->getFnParent();
12448
12449 // Look up the function name in the scope.
12450 Previous.clear(LookupLocalFriendName);
12451 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12452
12453 if (!Previous.empty()) {
12454 // All possible previous declarations must have the same context:
12455 // either they were declared at block scope or they are members of
12456 // one of the enclosing local classes.
12457 DC = Previous.getRepresentativeDecl()->getDeclContext();
12458 } else {
12459 // This is ill-formed, but provide the context that we would have
12460 // declared the function in, if we were permitted to, for error recovery.
12461 DC = FunctionContainingLocalClass;
12462 }
Richard Smith541b38b2013-09-20 01:15:31 +000012463 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012464
12465 // C++ [class.friend]p6:
12466 // A function can be defined in a friend declaration of a class if and
12467 // only if the class is a non-local class (9.8), the function name is
12468 // unqualified, and the function has namespace scope.
12469 if (D.isFunctionDefinition()) {
12470 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12471 }
12472
12473 // - There's no scope specifier, in which case we just go to the
12474 // appropriate scope and look for a function or function template
12475 // there as appropriate.
12476 } else if (SS.isInvalid() || !SS.isSet()) {
12477 // C++11 [namespace.memdef]p3:
12478 // If the name in a friend declaration is neither qualified nor
12479 // a template-id and the declaration is a function or an
12480 // elaborated-type-specifier, the lookup to determine whether
12481 // the entity has been previously declared shall not consider
12482 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012483 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012484
John McCallf7cfb222010-10-13 05:45:15 +000012485 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012486 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012487
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012488 // Skip class contexts. If someone can cite chapter and verse
12489 // for this behavior, that would be nice --- it's what GCC and
12490 // EDG do, and it seems like a reasonable intent, but the spec
12491 // really only says that checks for unqualified existing
12492 // declarations should stop at the nearest enclosing namespace,
12493 // not that they should only consider the nearest enclosing
12494 // namespace.
12495 while (DC->isRecord())
12496 DC = DC->getParent();
12497
12498 DeclContext *LookupDC = DC;
12499 while (LookupDC->isTransparentContext())
12500 LookupDC = LookupDC->getParent();
12501
12502 while (true) {
12503 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012504
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012505 if (!Previous.empty()) {
12506 DC = LookupDC;
12507 break;
John McCallf4776592010-10-14 22:22:28 +000012508 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012509
12510 if (isTemplateId) {
12511 if (isa<TranslationUnitDecl>(LookupDC)) break;
12512 } else {
12513 if (LookupDC->isFileContext()) break;
12514 }
12515 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012516 }
12517
John McCallccbc0322010-10-13 06:22:15 +000012518 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012519
John McCallde3fd222010-10-12 23:13:28 +000012520 // - There's a non-dependent scope specifier, in which case we
12521 // compute it and do a previous lookup there for a function
12522 // or function template.
12523 } else if (!SS.getScopeRep()->isDependent()) {
12524 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012525 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012526
Craig Topperc3ec1492014-05-26 06:22:03 +000012527 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012528
12529 LookupQualifiedName(Previous, DC);
12530
12531 // Ignore things found implicitly in the wrong scope.
12532 // TODO: better diagnostics for this case. Suggesting the right
12533 // qualified scope would be nice...
12534 LookupResult::Filter F = Previous.makeFilter();
12535 while (F.hasNext()) {
12536 NamedDecl *D = F.next();
12537 if (!DC->InEnclosingNamespaceSetOf(
12538 D->getDeclContext()->getRedeclContext()))
12539 F.erase();
12540 }
12541 F.done();
12542
12543 if (Previous.empty()) {
12544 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012545 Diag(Loc, diag::err_qualified_friend_not_found)
12546 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012547 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012548 }
12549
12550 // C++ [class.friend]p1: A friend of a class is a function or
12551 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012552 if (DC->Equals(CurContext))
12553 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012554 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012555 diag::warn_cxx98_compat_friend_is_member :
12556 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012557
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012558 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012559 // C++ [class.friend]p6:
12560 // A function can be defined in a friend declaration of a class if and
12561 // only if the class is a non-local class (9.8), the function name is
12562 // unqualified, and the function has namespace scope.
12563 SemaDiagnosticBuilder DB
12564 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12565
12566 DB << SS.getScopeRep();
12567 if (DC->isFileContext())
12568 DB << FixItHint::CreateRemoval(SS.getRange());
12569 SS.clear();
12570 }
John McCallde3fd222010-10-12 23:13:28 +000012571
12572 // - There's a scope specifier that does not match any template
12573 // parameter lists, in which case we use some arbitrary context,
12574 // create a method or method template, and wait for instantiation.
12575 // - There's a scope specifier that does match some template
12576 // parameter lists, which we don't handle right now.
12577 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012578 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012579 // C++ [class.friend]p6:
12580 // A function can be defined in a friend declaration of a class if and
12581 // only if the class is a non-local class (9.8), the function name is
12582 // unqualified, and the function has namespace scope.
12583 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12584 << SS.getScopeRep();
12585 }
12586
John McCallde3fd222010-10-12 23:13:28 +000012587 DC = CurContext;
12588 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012589 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012590
John McCallf7cfb222010-10-13 05:45:15 +000012591 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012592 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012593 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12594 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12595 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012596 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012597 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12598 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012599 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012600 }
John McCall07e91c02009-08-06 02:15:43 +000012601 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012602
Douglas Gregordd847ba2011-11-03 16:37:14 +000012603 // FIXME: This is an egregious hack to cope with cases where the scope stack
12604 // does not contain the declaration context, i.e., in an out-of-line
12605 // definition of a class.
12606 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12607 if (!DCScope) {
12608 FakeDCScope.setEntity(DC);
12609 DCScope = &FakeDCScope;
12610 }
Richard Smith114394f2013-08-09 04:35:01 +000012611
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012612 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012613 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012614 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012615 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012616
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012617 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012618
Richard Smith114394f2013-08-09 04:35:01 +000012619 // If we performed typo correction, we might have added a scope specifier
12620 // and changed the decl context.
12621 DC = ND->getDeclContext();
12622
John McCall759e32b2009-08-31 22:39:49 +000012623 // Add the function declaration to the appropriate lookup tables,
12624 // adjusting the redeclarations list as necessary. We don't
12625 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012626 //
John McCall759e32b2009-08-31 22:39:49 +000012627 // Also update the scope-based lookup if the target context's
12628 // lookup context is in lexical scope.
12629 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012630 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012631 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012632 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012633 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012634 }
John McCallaa74a0c2009-08-28 07:59:38 +000012635
12636 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012637 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012638 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012639 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012640 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012641
John McCalla0a96892012-08-10 03:15:35 +000012642 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012643 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012644 } else {
12645 if (DC->isRecord()) CheckFriendAccess(ND);
12646
John McCall2c2eb122010-10-16 06:59:13 +000012647 FunctionDecl *FD;
12648 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12649 FD = FTD->getTemplatedDecl();
12650 else
12651 FD = cast<FunctionDecl>(ND);
12652
David Majnemer502b0ed2013-06-25 23:09:30 +000012653 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12654 // default argument expression, that declaration shall be a definition
12655 // and shall be the only declaration of the function or function
12656 // template in the translation unit.
12657 if (functionDeclHasDefaultArgument(FD)) {
12658 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12659 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12660 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12661 } else if (!D.isFunctionDefinition())
12662 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12663 }
12664
John McCall2c2eb122010-10-16 06:59:13 +000012665 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012666 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12667 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12668 << SS.getScopeRep() << SS.getRange()
12669 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012670 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012671 }
John McCall2c2eb122010-10-16 06:59:13 +000012672 }
John McCallde3fd222010-10-12 23:13:28 +000012673
John McCall48871652010-08-21 09:40:31 +000012674 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012675}
12676
John McCall48871652010-08-21 09:40:31 +000012677void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12678 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012679
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012680 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012681 if (!Fn) {
12682 Diag(DelLoc, diag::err_deleted_non_function);
12683 return;
12684 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012685
Douglas Gregorec9fd132012-01-14 16:38:05 +000012686 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012687 // Don't consider the implicit declaration we generate for explicit
12688 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012689 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12690 Prev->getPreviousDecl()) &&
12691 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012692 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012693 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12694 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12695 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012696 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012697 // If the declaration wasn't the first, we delete the function anyway for
12698 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012699 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012700 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012701
Nico Rieck9de0a572014-05-29 16:51:19 +000012702 // dllimport/dllexport cannot be deleted.
12703 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12704 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12705 Fn->setInvalidDecl();
12706 }
12707
Richard Smithb4d2a152013-04-02 19:38:47 +000012708 if (Fn->isDeleted())
12709 return;
12710
12711 // See if we're deleting a function which is already known to override a
12712 // non-deleted virtual function.
12713 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12714 bool IssuedDiagnostic = false;
12715 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12716 E = MD->end_overridden_methods();
12717 I != E; ++I) {
12718 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12719 if (!IssuedDiagnostic) {
12720 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12721 IssuedDiagnostic = true;
12722 }
12723 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12724 }
12725 }
12726 }
12727
Richard Smithb63b6ee2014-01-22 01:43:19 +000012728 // C++11 [basic.start.main]p3:
12729 // A program that defines main as deleted [...] is ill-formed.
12730 if (Fn->isMain())
12731 Diag(DelLoc, diag::err_deleted_main);
12732
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012733 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012734}
Sebastian Redl4c018662009-04-27 21:33:24 +000012735
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012736void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012737 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012738
12739 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012740 if (MD->getParent()->isDependentType()) {
12741 MD->setDefaulted();
12742 MD->setExplicitlyDefaulted();
12743 return;
12744 }
12745
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012746 CXXSpecialMember Member = getSpecialMember(MD);
12747 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012748 if (!MD->isInvalidDecl())
12749 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012750 return;
12751 }
12752
12753 MD->setDefaulted();
12754 MD->setExplicitlyDefaulted();
12755
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012756 // If this definition appears within the record, do the checking when
12757 // the record is complete.
12758 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012759 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012760 // Find the uninstantiated declaration that actually had the '= default'
12761 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012762 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012763
Richard Smith3901dfe2013-03-27 00:22:47 +000012764 // If the method was defaulted on its first declaration, we will have
12765 // already performed the checking in CheckCompletedCXXClass. Such a
12766 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012767 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012768 return;
12769
Richard Smithd3b5c9082012-07-27 04:22:15 +000012770 CheckExplicitlyDefaultedSpecialMember(MD);
12771
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012772 if (MD->isInvalidDecl())
12773 return;
12774
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012775 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012776 case CXXDefaultConstructor:
12777 DefineImplicitDefaultConstructor(DefaultLoc,
12778 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012779 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012780 case CXXCopyConstructor:
12781 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012782 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012783 case CXXCopyAssignment:
12784 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012785 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012786 case CXXDestructor:
12787 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012788 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012789 case CXXMoveConstructor:
12790 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012791 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012792 case CXXMoveAssignment:
12793 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012794 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012795 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012796 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012797 }
12798 } else {
12799 Diag(DefaultLoc, diag::err_default_special_members);
12800 }
12801}
12802
Sebastian Redl4c018662009-04-27 21:33:24 +000012803static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012804 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012805 Stmt *SubStmt = *CI;
12806 if (!SubStmt)
12807 continue;
12808 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012809 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012810 diag::err_return_in_constructor_handler);
12811 if (!isa<Expr>(SubStmt))
12812 SearchForReturnInStmt(Self, SubStmt);
12813 }
12814}
12815
12816void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12817 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12818 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12819 SearchForReturnInStmt(*this, Handler);
12820 }
12821}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012822
David Blaikie68f71a32013-01-18 23:03:15 +000012823bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012824 const CXXMethodDecl *Old) {
12825 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12826 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12827
12828 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12829
12830 // If the calling conventions match, everything is fine
12831 if (NewCC == OldCC)
12832 return false;
12833
Hans Wennborg2545efe2013-12-11 17:42:11 +000012834 // If the calling conventions mismatch because the new function is static,
12835 // suppress the calling convention mismatch error; the error about static
12836 // function override (err_static_overrides_virtual from
12837 // Sema::CheckFunctionDeclaration) is more clear.
12838 if (New->getStorageClass() == SC_Static)
12839 return false;
12840
Reid Kleckner78af0702013-08-27 23:08:25 +000012841 Diag(New->getLocation(),
12842 diag::err_conflicting_overriding_cc_attributes)
12843 << New->getDeclName() << New->getType() << Old->getType();
12844 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12845 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012846}
12847
Mike Stump11289f42009-09-09 15:08:12 +000012848bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012849 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012850 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12851 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012852
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012853 if (Context.hasSameType(NewTy, OldTy) ||
12854 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012855 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012856
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012857 // Check if the return types are covariant
12858 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012859
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012860 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012861 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12862 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012863 NewClassTy = NewPT->getPointeeType();
12864 OldClassTy = OldPT->getPointeeType();
12865 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012866 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12867 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12868 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12869 NewClassTy = NewRT->getPointeeType();
12870 OldClassTy = OldRT->getPointeeType();
12871 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012872 }
12873 }
Mike Stump11289f42009-09-09 15:08:12 +000012874
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012875 // The return types aren't either both pointers or references to a class type.
12876 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012877 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012878 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012879 << New->getDeclName() << NewTy << OldTy
12880 << New->getReturnTypeSourceRange();
12881 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12882 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012883
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012884 return true;
12885 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012886
Anders Carlssone60365b2009-12-31 18:34:24 +000012887 // C++ [class.virtual]p6:
12888 // If the return type of D::f differs from the return type of B::f, the
12889 // class type in the return type of D::f shall be complete at the point of
12890 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012891 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12892 if (!RT->isBeingDefined() &&
12893 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012894 diag::err_covariant_return_incomplete,
12895 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012896 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012897 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012898
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012899 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012900 // Check if the new class derives from the old class.
12901 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012902 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12903 << New->getDeclName() << NewTy << OldTy
12904 << New->getReturnTypeSourceRange();
12905 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12906 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012907 return true;
12908 }
Mike Stump11289f42009-09-09 15:08:12 +000012909
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012910 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012911 if (CheckDerivedToBaseConversion(
12912 NewClassTy, OldClassTy,
12913 diag::err_covariant_return_inaccessible_base,
12914 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12915 New->getLocation(), New->getReturnTypeSourceRange(),
12916 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012917 // FIXME: this note won't trigger for delayed access control
12918 // diagnostics, and it's impossible to get an undelayed error
12919 // here from access control during the original parse because
12920 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012921 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12922 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012923 return true;
12924 }
12925 }
Mike Stump11289f42009-09-09 15:08:12 +000012926
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012927 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012928 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012929 Diag(New->getLocation(),
12930 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012931 << New->getDeclName() << NewTy << OldTy
12932 << New->getReturnTypeSourceRange();
12933 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12934 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012935 return true;
12936 };
Mike Stump11289f42009-09-09 15:08:12 +000012937
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012938
12939 // The new class type must have the same or less qualifiers as the old type.
12940 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12941 Diag(New->getLocation(),
12942 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012943 << New->getDeclName() << NewTy << OldTy
12944 << New->getReturnTypeSourceRange();
12945 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12946 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012947 return true;
12948 };
Mike Stump11289f42009-09-09 15:08:12 +000012949
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012950 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012951}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012952
Douglas Gregor21920e372009-12-01 17:24:26 +000012953/// \brief Mark the given method pure.
12954///
12955/// \param Method the method to be marked pure.
12956///
12957/// \param InitRange the source range that covers the "0" initializer.
12958bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012959 SourceLocation EndLoc = InitRange.getEnd();
12960 if (EndLoc.isValid())
12961 Method->setRangeEnd(EndLoc);
12962
Douglas Gregor21920e372009-12-01 17:24:26 +000012963 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12964 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012965 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012966 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012967
12968 if (!Method->isInvalidDecl())
12969 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12970 << Method->getDeclName() << InitRange;
12971 return true;
12972}
12973
Douglas Gregor926410d2012-02-21 02:22:07 +000012974/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012975static bool isStaticDataMember(const Decl *D) {
12976 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12977 return Var->isStaticDataMember();
12978
12979 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012980}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012981
John McCall1f4ee7b2009-12-19 09:28:58 +000012982/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12983/// an initializer for the out-of-line declaration 'Dcl'. The scope
12984/// is a fresh scope pushed for just this purpose.
12985///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012986/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12987/// static data member of class X, names should be looked up in the scope of
12988/// class X.
John McCall48871652010-08-21 09:40:31 +000012989void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012990 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012991 if (!D || D->isInvalidDecl())
12992 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012993
Richard Smitha2302242013-12-05 07:51:02 +000012994 // We will always have a nested name specifier here, but this declaration
12995 // might not be out of line if the specifier names the current namespace:
12996 // extern int n;
12997 // int ::n = 0;
12998 if (D->isOutOfLine())
12999 EnterDeclaratorContext(S, D->getDeclContext());
13000
Douglas Gregor926410d2012-02-21 02:22:07 +000013001 // If we are parsing the initializer for a static data member, push a
13002 // new expression evaluation context that is associated with this static
13003 // data member.
13004 if (isStaticDataMember(D))
13005 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013006}
13007
13008/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013009/// initializer for the out-of-line declaration 'D'.
13010void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013011 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013012 if (!D || D->isInvalidDecl())
13013 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013014
Douglas Gregor926410d2012-02-21 02:22:07 +000013015 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013016 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013017
Richard Smitha2302242013-12-05 07:51:02 +000013018 if (D->isOutOfLine())
13019 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013020}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013021
13022/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13023/// C++ if/switch/while/for statement.
13024/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013025DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013026 // C++ 6.4p2:
13027 // The declarator shall not specify a function or an array.
13028 // The type-specifier-seq shall not contain typedef and shall not declare a
13029 // new class or enumeration.
13030 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13031 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013032
13033 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013034 if (!Dcl)
13035 return true;
13036
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013037 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13038 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013039 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013040 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013041 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013042
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013043 return Dcl;
13044}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013045
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013046void Sema::LoadExternalVTableUses() {
13047 if (!ExternalSource)
13048 return;
13049
13050 SmallVector<ExternalVTableUse, 4> VTables;
13051 ExternalSource->ReadUsedVTables(VTables);
13052 SmallVector<VTableUse, 4> NewUses;
13053 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13054 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13055 = VTablesUsed.find(VTables[I].Record);
13056 // Even if a definition wasn't required before, it may be required now.
13057 if (Pos != VTablesUsed.end()) {
13058 if (!Pos->second && VTables[I].DefinitionRequired)
13059 Pos->second = true;
13060 continue;
13061 }
13062
13063 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13064 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13065 }
13066
13067 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13068}
13069
Douglas Gregor88d292c2010-05-13 16:44:06 +000013070void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13071 bool DefinitionRequired) {
13072 // Ignore any vtable uses in unevaluated operands or for classes that do
13073 // not have a vtable.
13074 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013075 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013076 return;
13077
Douglas Gregor88d292c2010-05-13 16:44:06 +000013078 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013079 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013080 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13081 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13082 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13083 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013084 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013085 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013086 // list, since we may have already processed the first entry.
13087 if (DefinitionRequired && !Pos.first->second) {
13088 Pos.first->second = true;
13089 } else {
13090 // Otherwise, we can early exit.
13091 return;
13092 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013093 } else {
13094 // The Microsoft ABI requires that we perform the destructor body
13095 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13096 // the deleting destructor is emitted with the vtable, not with the
13097 // destructor definition as in the Itanium ABI.
13098 // If it has a definition, we do the check at that point instead.
13099 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13100 Class->hasUserDeclaredDestructor() &&
13101 !Class->getDestructor()->isDefined() &&
13102 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013103 CXXDestructorDecl *DD = Class->getDestructor();
13104 ContextRAII SavedContext(*this, DD);
13105 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013106 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013107 }
13108
13109 // Local classes need to have their virtual members marked
13110 // immediately. For all other classes, we mark their virtual members
13111 // at the end of the translation unit.
13112 if (Class->isLocalClass())
13113 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013114 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013115 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013116}
13117
Douglas Gregor88d292c2010-05-13 16:44:06 +000013118bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013119 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013120 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013121 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013122
Douglas Gregor88d292c2010-05-13 16:44:06 +000013123 // Note: The VTableUses vector could grow as a result of marking
13124 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013125 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013126 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013127 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013128 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013129 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013130 if (!Class)
13131 continue;
13132
13133 SourceLocation Loc = VTableUses[I].second;
13134
Richard Smithd3b5c9082012-07-27 04:22:15 +000013135 bool DefineVTable = true;
13136
Douglas Gregor88d292c2010-05-13 16:44:06 +000013137 // If this class has a key function, but that key function is
13138 // defined in another translation unit, we don't need to emit the
13139 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013140 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013141 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013142 // The key function is in another translation unit.
13143 DefineVTable = false;
13144 TemplateSpecializationKind TSK =
13145 KeyFunction->getTemplateSpecializationKind();
13146 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13147 TSK != TSK_ImplicitInstantiation &&
13148 "Instantiations don't have key functions");
13149 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013150 } else if (!KeyFunction) {
13151 // If we have a class with no key function that is the subject
13152 // of an explicit instantiation declaration, suppress the
13153 // vtable; it will live with the explicit instantiation
13154 // definition.
13155 bool IsExplicitInstantiationDeclaration
13156 = Class->getTemplateSpecializationKind()
13157 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013158 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013159 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013160 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013161 if (TSK == TSK_ExplicitInstantiationDeclaration)
13162 IsExplicitInstantiationDeclaration = true;
13163 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13164 IsExplicitInstantiationDeclaration = false;
13165 break;
13166 }
13167 }
13168
13169 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013170 DefineVTable = false;
13171 }
13172
13173 // The exception specifications for all virtual members may be needed even
13174 // if we are not providing an authoritative form of the vtable in this TU.
13175 // We may choose to emit it available_externally anyway.
13176 if (!DefineVTable) {
13177 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13178 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013179 }
13180
13181 // Mark all of the virtual members of this class as referenced, so
13182 // that we can build a vtable. Then, tell the AST consumer that a
13183 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013184 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013185 MarkVirtualMembersReferenced(Loc, Class);
13186 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013187 if (VTablesUsed[Canonical])
13188 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013189
13190 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013191 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013192 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013193 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013194 if (!KeyFunction ||
13195 (KeyFunction->hasBody(KeyFunctionDef) &&
13196 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013197 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13198 TSK_ExplicitInstantiationDefinition
13199 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13200 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013201 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013202 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013203 VTableUses.clear();
13204
Douglas Gregor97509692011-04-22 22:25:37 +000013205 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013206}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013207
Richard Smithd3b5c9082012-07-27 04:22:15 +000013208void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13209 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013210 for (const auto *I : RD->methods())
13211 if (I->isVirtual() && !I->isPure())
13212 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013213}
13214
Rafael Espindola5b334082010-03-26 00:36:59 +000013215void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13216 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013217 // Mark all functions which will appear in RD's vtable as used.
13218 CXXFinalOverriderMap FinalOverriders;
13219 RD->getFinalOverriders(FinalOverriders);
13220 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13221 E = FinalOverriders.end();
13222 I != E; ++I) {
13223 for (OverridingMethods::const_iterator OI = I->second.begin(),
13224 OE = I->second.end();
13225 OI != OE; ++OI) {
13226 assert(OI->second.size() > 0 && "no final overrider");
13227 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013228
Richard Smith4ff9ff92012-07-07 06:59:51 +000013229 // C++ [basic.def.odr]p2:
13230 // [...] A virtual member function is used if it is not pure. [...]
13231 if (!Overrider->isPure())
13232 MarkFunctionReferenced(Loc, Overrider);
13233 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013234 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013235
13236 // Only classes that have virtual bases need a VTT.
13237 if (RD->getNumVBases() == 0)
13238 return;
13239
Aaron Ballman574705e2014-03-13 15:41:46 +000013240 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013241 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013242 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013243 if (Base->getNumVBases() == 0)
13244 continue;
13245 MarkVirtualMembersReferenced(Loc, Base);
13246 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013247}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013248
13249/// SetIvarInitializers - This routine builds initialization ASTs for the
13250/// Objective-C implementation whose ivars need be initialized.
13251void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013252 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013253 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013254 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013255 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013256 CollectIvarsToConstructOrDestruct(OID, ivars);
13257 if (ivars.empty())
13258 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013259 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013260 for (unsigned i = 0; i < ivars.size(); i++) {
13261 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013262 if (Field->isInvalidDecl())
13263 continue;
13264
Alexis Hunt1d792652011-01-08 20:30:50 +000013265 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013266 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13267 InitializationKind InitKind =
13268 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013269
13270 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13271 ExprResult MemberInit =
13272 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013273 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013274 // Note, MemberInit could actually come back empty if no initialization
13275 // is required (e.g., because it would call a trivial default constructor)
13276 if (!MemberInit.get() || MemberInit.isInvalid())
13277 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013278
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013279 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013280 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13281 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013282 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013283 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013284 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013285
13286 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013287 if (const RecordType *RecordTy =
13288 Context.getBaseElementType(Field->getType())
13289 ->getAs<RecordType>()) {
13290 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013291 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013292 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013293 CheckDestructorAccess(Field->getLocation(), Destructor,
13294 PDiag(diag::err_access_dtor_ivar)
13295 << Context.getBaseElementType(Field->getType()));
13296 }
13297 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013298 }
13299 ObjCImplementation->setIvarInitializers(Context,
13300 AllToInit.data(), AllToInit.size());
13301 }
13302}
Alexis Hunt6118d662011-05-04 05:57:24 +000013303
Alexis Hunt27a761d2011-05-04 23:29:54 +000013304static
13305void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13306 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13307 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13308 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13309 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013310 if (Ctor->isInvalidDecl())
13311 return;
13312
Richard Smith802c4b72012-08-23 06:16:52 +000013313 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13314
13315 // Target may not be determinable yet, for instance if this is a dependent
13316 // call in an uninstantiated template.
13317 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013318 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013319 (void)Target->hasBody(FNTarget);
13320 Target = const_cast<CXXConstructorDecl*>(
13321 cast_or_null<CXXConstructorDecl>(FNTarget));
13322 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013323
13324 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13325 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013326 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013327
David Blaikie82e95a32014-11-19 07:49:47 +000013328 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013329 return;
13330
13331 // We know that beyond here, we aren't chaining into a cycle.
13332 if (!Target || !Target->isDelegatingConstructor() ||
13333 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013334 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013335 Current.clear();
13336 // We've hit a cycle.
13337 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13338 Current.count(TCanonical)) {
13339 // If we haven't diagnosed this cycle yet, do so now.
13340 if (!Invalid.count(TCanonical)) {
13341 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013342 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013343 << Ctor;
13344
Richard Smith802c4b72012-08-23 06:16:52 +000013345 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013346 if (TCanonical != Canonical)
13347 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13348
13349 CXXConstructorDecl *C = Target;
13350 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013351 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013352 (void)C->getTargetConstructor()->hasBody(FNTarget);
13353 assert(FNTarget && "Ctor cycle through bodiless function");
13354
Richard Smith802c4b72012-08-23 06:16:52 +000013355 C = const_cast<CXXConstructorDecl*>(
13356 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013357 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13358 }
13359 }
13360
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013361 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013362 Current.clear();
13363 } else {
13364 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13365 }
13366}
13367
13368
Alexis Hunt6118d662011-05-04 05:57:24 +000013369void Sema::CheckDelegatingCtorCycles() {
13370 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13371
Douglas Gregorbae31202011-07-27 21:57:17 +000013372 for (DelegatingCtorDeclsType::iterator
13373 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013374 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013375 I != E; ++I)
13376 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013377
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013378 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13379 CE = Invalid.end();
13380 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013381 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013382}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013383
Douglas Gregor3024f072012-04-16 07:05:22 +000013384namespace {
13385 /// \brief AST visitor that finds references to the 'this' expression.
13386 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13387 Sema &S;
13388
13389 public:
13390 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13391
13392 bool VisitCXXThisExpr(CXXThisExpr *E) {
13393 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13394 << E->isImplicit();
13395 return false;
13396 }
13397 };
13398}
13399
13400bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13401 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13402 if (!TSInfo)
13403 return false;
13404
13405 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013406 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013407 if (!ProtoTL)
13408 return false;
13409
13410 // C++11 [expr.prim.general]p3:
13411 // [The expression this] shall not appear before the optional
13412 // cv-qualifier-seq and it shall not appear within the declaration of a
13413 // static member function (although its type and value category are defined
13414 // within a static member function as they are within a non-static member
13415 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013416 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013417 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013418 FindCXXThisExpr Finder(*this);
13419
13420 // If the return type came after the cv-qualifier-seq, check it now.
13421 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013422 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013423 return true;
13424
13425 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013426 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13427 return true;
13428
13429 return checkThisInStaticMemberFunctionAttributes(Method);
13430}
13431
13432bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13433 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13434 if (!TSInfo)
13435 return false;
13436
13437 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013438 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013439 if (!ProtoTL)
13440 return false;
13441
David Blaikie6adc78e2013-02-18 22:06:02 +000013442 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013443 FindCXXThisExpr Finder(*this);
13444
Douglas Gregor3024f072012-04-16 07:05:22 +000013445 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013446 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013447 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013448 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013449 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013450 case EST_DynamicNone:
13451 case EST_MSAny:
13452 case EST_None:
13453 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013454
Douglas Gregor3024f072012-04-16 07:05:22 +000013455 case EST_ComputedNoexcept:
13456 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13457 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013458
Douglas Gregor3024f072012-04-16 07:05:22 +000013459 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013460 for (const auto &E : Proto->exceptions()) {
13461 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013462 return true;
13463 }
13464 break;
13465 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013466
13467 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013468}
13469
13470bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13471 FindCXXThisExpr Finder(*this);
13472
13473 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013474 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013475 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013476 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013477 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013478 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013479 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013480 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013481 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013482 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013483 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013484 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013485 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013486 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013487 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013488 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013489 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013490 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013491 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013492 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013493 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013494 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013495 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013496 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013497 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013498 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013499 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013500 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013501 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013502 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013503 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013504
13505 if (Arg && !Finder.TraverseStmt(Arg))
13506 return true;
13507
13508 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13509 if (!Finder.TraverseStmt(Args[I]))
13510 return true;
13511 }
13512 }
13513
13514 return false;
13515}
13516
Richard Smith2e321552014-11-12 02:00:47 +000013517void Sema::checkExceptionSpecification(
13518 bool IsTopLevel, ExceptionSpecificationType EST,
13519 ArrayRef<ParsedType> DynamicExceptions,
13520 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13521 SmallVectorImpl<QualType> &Exceptions,
13522 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013523 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013524 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013525 if (EST == EST_Dynamic) {
13526 Exceptions.reserve(DynamicExceptions.size());
13527 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13528 // FIXME: Preserve type source info.
13529 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13530
Richard Smith2e321552014-11-12 02:00:47 +000013531 if (IsTopLevel) {
13532 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13533 collectUnexpandedParameterPacks(ET, Unexpanded);
13534 if (!Unexpanded.empty()) {
13535 DiagnoseUnexpandedParameterPacks(
13536 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13537 Unexpanded);
13538 continue;
13539 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013540 }
13541
13542 // Check that the type is valid for an exception spec, and
13543 // drop it if not.
13544 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13545 Exceptions.push_back(ET);
13546 }
Richard Smith8acb4282014-07-31 21:57:55 +000013547 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013548 return;
13549 }
Richard Smith8acb4282014-07-31 21:57:55 +000013550
Douglas Gregor433e0532012-04-16 18:27:27 +000013551 if (EST == EST_ComputedNoexcept) {
13552 // If an error occurred, there's no expression here.
13553 if (NoexceptExpr) {
13554 assert((NoexceptExpr->isTypeDependent() ||
13555 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13556 Context.BoolTy) &&
13557 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013558 if (IsTopLevel && NoexceptExpr &&
13559 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013560 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013561 return;
13562 }
Richard Smith8acb4282014-07-31 21:57:55 +000013563
Douglas Gregor433e0532012-04-16 18:27:27 +000013564 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013565 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013566 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013567 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013568 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013569 }
13570 return;
13571 }
13572}
13573
Richard Smith0b3a4622014-11-13 20:01:57 +000013574void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13575 ExceptionSpecificationType EST,
13576 SourceRange SpecificationRange,
13577 ArrayRef<ParsedType> DynamicExceptions,
13578 ArrayRef<SourceRange> DynamicExceptionRanges,
13579 Expr *NoexceptExpr) {
13580 if (!MethodD)
13581 return;
13582
13583 // Dig out the method we're referring to.
13584 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13585 MethodD = FunTmpl->getTemplatedDecl();
13586
13587 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13588 if (!Method)
13589 return;
13590
13591 // Check the exception specification.
13592 llvm::SmallVector<QualType, 4> Exceptions;
13593 FunctionProtoType::ExceptionSpecInfo ESI;
13594 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13595 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13596 ESI);
13597
13598 // Update the exception specification on the function type.
13599 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13600
13601 if (Method->isStatic())
13602 checkThisInStaticMemberFunctionExceptionSpec(Method);
13603
13604 if (Method->isVirtual()) {
13605 // Check overrides, which we previously had to delay.
13606 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13607 OEnd = Method->end_overridden_methods();
13608 O != OEnd; ++O)
13609 CheckOverridingFunctionExceptionSpec(Method, *O);
13610 }
13611}
13612
John McCall5e77d762013-04-16 07:28:30 +000013613/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13614///
13615MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13616 SourceLocation DeclStart,
13617 Declarator &D, Expr *BitWidth,
13618 InClassInitStyle InitStyle,
13619 AccessSpecifier AS,
13620 AttributeList *MSPropertyAttr) {
13621 IdentifierInfo *II = D.getIdentifier();
13622 if (!II) {
13623 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013624 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013625 }
13626 SourceLocation Loc = D.getIdentifierLoc();
13627
13628 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13629 QualType T = TInfo->getType();
13630 if (getLangOpts().CPlusPlus) {
13631 CheckExtraCXXDefaultArguments(D);
13632
13633 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13634 UPPC_DataMemberType)) {
13635 D.setInvalidType();
13636 T = Context.IntTy;
13637 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13638 }
13639 }
13640
13641 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13642
13643 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13644 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13645 diag::err_invalid_thread)
13646 << DeclSpec::getSpecifierName(TSCS);
13647
13648 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013649 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013650 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13651 LookupName(Previous, S);
13652 switch (Previous.getResultKind()) {
13653 case LookupResult::Found:
13654 case LookupResult::FoundUnresolvedValue:
13655 PrevDecl = Previous.getAsSingle<NamedDecl>();
13656 break;
13657
13658 case LookupResult::FoundOverloaded:
13659 PrevDecl = Previous.getRepresentativeDecl();
13660 break;
13661
13662 case LookupResult::NotFound:
13663 case LookupResult::NotFoundInCurrentInstantiation:
13664 case LookupResult::Ambiguous:
13665 break;
13666 }
13667
13668 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13669 // Maybe we will complain about the shadowed template parameter.
13670 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13671 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013672 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013673 }
13674
13675 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013676 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013677
13678 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013679 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013680 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13681 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013682 ProcessDeclAttributes(TUScope, NewPD, D);
13683 NewPD->setAccess(AS);
13684
13685 if (NewPD->isInvalidDecl())
13686 Record->setInvalidDecl();
13687
13688 if (D.getDeclSpec().isModulePrivateSpecified())
13689 NewPD->setModulePrivate();
13690
13691 if (NewPD->isInvalidDecl() && PrevDecl) {
13692 // Don't introduce NewFD into scope; there's already something
13693 // with the same name in the same scope.
13694 } else if (II) {
13695 PushOnScopeChains(NewPD, S);
13696 } else
13697 Record->addDecl(NewPD);
13698
13699 return NewPD;
13700}