blob: 82407250657d8876148641c0942aaf9fb1286f58 [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;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000394 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000395 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000400 }
401 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemer502b0ed2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Toppere4794282012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner199abbc2008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000444 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloye9430032012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
Richard Smith541b38b2013-09-20 01:15:31 +0000452 // The declaration context corresponding to the scope is the semantic
453 // parent, unless this is a local function declaration, in which case
454 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000455 DeclContext *ScopeDC = New->isLocalExternDecl()
456 ? New->getLexicalDeclContext()
457 : New->getDeclContext();
458 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000459 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000460 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000461 // the same scope and this is not an out-of-line definition of
462 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000463 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000464 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
465 // If only one of these is a local function declaration, then they are
466 // declared in different scopes, even though isDeclInScope may think
467 // they're in the same scope. (If both are local, the scope check is
468 // sufficent, and if neither is local, then they are in the same scope.)
469 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000470
471 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000472
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 unsigned DiagDefaultParamID =
474 diag::err_param_default_argument_redefinition;
475
476 // MSVC accepts that default parameters be redefined for member functions
477 // of template class. The new default parameter's value is ignored.
478 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000479 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000480 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
481 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000482 // Merge the old default argument into the new parameter.
483 NewParam->setHasInheritedDefaultArg();
484 if (OldParam->hasUninstantiatedDefaultArg())
485 NewParam->setUninstantiatedDefaultArg(
486 OldParam->getUninstantiatedDefaultArg());
487 else
488 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000489 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000490 Invalid = false;
491 }
492 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000493
Francois Pichet8cb243a2011-04-10 04:58:30 +0000494 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
495 // hint here. Alternatively, we could walk the type-source information
496 // for NewParam to find the last source location in the type... but it
497 // isn't worth the effort right now. This is the kind of test case that
498 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000499 // int f(int);
500 // void g(int (*fp)(int) = f);
501 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000502 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000503 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000504
505 // Look for the function declaration where the default argument was
506 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000507 for (FunctionDecl *Older = Old->getPreviousDecl();
508 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000509 if (!Older->getParamDecl(p)->hasDefaultArg())
510 break;
511
512 OldParam = Older->getParamDecl(p);
513 }
514
515 Diag(OldParam->getLocation(), diag::note_previous_definition)
516 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000517 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000518 // Merge the old default argument into the new parameter.
519 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000520 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000521 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000522 if (OldParam->hasUninstantiatedDefaultArg())
523 NewParam->setUninstantiatedDefaultArg(
524 OldParam->getUninstantiatedDefaultArg());
525 else
John McCalle61b02b2010-05-04 01:53:42 +0000526 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000527 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000528 if (New->getDescribedFunctionTemplate()) {
529 // Paragraph 4, quoted above, only applies to non-template functions.
530 Diag(NewParam->getLocation(),
531 diag::err_param_default_argument_template_redecl)
532 << NewParam->getDefaultArgRange();
533 Diag(Old->getLocation(), diag::note_template_prev_declaration)
534 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 } else if (New->getTemplateSpecializationKind()
536 != TSK_ImplicitInstantiation &&
537 New->getTemplateSpecializationKind() != TSK_Undeclared) {
538 // C++ [temp.expr.spec]p21:
539 // Default function arguments shall not be specified in a declaration
540 // or a definition for one of the following explicit specializations:
541 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000542 // - the explicit specialization of a member function template;
543 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000544 // template where the class template specialization to which the
545 // member function specialization belongs is implicitly
546 // instantiated.
547 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
548 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
549 << New->getDeclName()
550 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000551 } else if (New->getDeclContext()->isDependentContext()) {
552 // C++ [dcl.fct.default]p6 (DR217):
553 // Default arguments for a member function of a class template shall
554 // be specified on the initial declaration of the member function
555 // within the class template.
556 //
557 // Reading the tea leaves a bit in DR217 and its reference to DR205
558 // leads me to the conclusion that one cannot add default function
559 // arguments for an out-of-line definition of a member function of a
560 // dependent type.
561 int WhichKind = 2;
562 if (CXXRecordDecl *Record
563 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
564 if (Record->getDescribedClassTemplate())
565 WhichKind = 0;
566 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
567 WhichKind = 1;
568 else
569 WhichKind = 2;
570 }
571
572 Diag(NewParam->getLocation(),
573 diag::err_param_default_argument_member_template_redecl)
574 << WhichKind
575 << NewParam->getDefaultArgRange();
576 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000577 }
578 }
579
Richard Smith58c3cc12012-11-28 03:45:24 +0000580 // DR1344: If a default argument is added outside a class definition and that
581 // default argument makes the function a special member function, the program
582 // is ill-formed. This can only happen for constructors.
583 if (isa<CXXConstructorDecl>(New) &&
584 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
585 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
586 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
587 if (NewSM != OldSM) {
588 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
589 assert(NewParam->hasDefaultArg());
590 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
591 << NewParam->getDefaultArgRange() << NewSM;
592 Diag(Old->getLocation(), diag::note_previous_declaration);
593 }
594 }
595
David Majnemeree4f4022014-03-30 06:44:54 +0000596 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000597 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000598 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000599 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000600 if (New->isConstexpr() != Old->isConstexpr()) {
601 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
602 << New << New->isConstexpr();
603 Diag(Old->getLocation(), diag::note_previous_declaration);
604 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000605 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
606 // C++11 [dcl.fcn.spec]p4:
607 // If the definition of a function appears in a translation unit before its
608 // first declaration as inline, the program is ill-formed.
609 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
610 Diag(Def->getLocation(), diag::note_previous_definition);
611 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000612 }
613
David Majnemer502b0ed2013-06-25 23:09:30 +0000614 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000615 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000616 // the only declaration of the function or function template in the
617 // translation unit.
618 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
619 functionDeclHasDefaultArgument(Old)) {
620 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
621 Diag(Old->getLocation(), diag::note_previous_declaration);
622 Invalid = true;
623 }
624
Douglas Gregorf40863c2010-02-12 07:32:17 +0000625 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000626 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000627
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000628 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000629}
630
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000631/// \brief Merge the exception specifications of two variable declarations.
632///
633/// This is called when there's a redeclaration of a VarDecl. The function
634/// checks if the redeclaration might have an exception specification and
635/// validates compatibility and merges the specs if necessary.
636void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
637 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000638 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000639 return;
640
641 assert(Context.hasSameType(New->getType(), Old->getType()) &&
642 "Should only be called if types are otherwise the same.");
643
644 QualType NewType = New->getType();
645 QualType OldType = Old->getType();
646
647 // We're only interested in pointers and references to functions, as well
648 // as pointers to member functions.
649 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
650 NewType = R->getPointeeType();
651 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
652 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
653 NewType = P->getPointeeType();
654 OldType = OldType->getAs<PointerType>()->getPointeeType();
655 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
656 NewType = M->getPointeeType();
657 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
658 }
659
660 if (!NewType->isFunctionProtoType())
661 return;
662
663 // There's lots of special cases for functions. For function pointers, system
664 // libraries are hopefully not as broken so that we don't need these
665 // workarounds.
666 if (CheckEquivalentExceptionSpec(
667 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
668 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
669 New->setInvalidDecl();
670 }
671}
672
Chris Lattner199abbc2008-04-08 05:04:30 +0000673/// CheckCXXDefaultArguments - Verify that the default arguments for a
674/// function declaration are well-formed according to C++
675/// [dcl.fct.default].
676void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
677 unsigned NumParams = FD->getNumParams();
678 unsigned p;
679
680 // Find first parameter with a default argument
681 for (p = 0; p < NumParams; ++p) {
682 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000683 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000684 break;
685 }
686
687 // C++ [dcl.fct.default]p4:
688 // In a given function declaration, all parameters
689 // subsequent to a parameter with a default argument shall
690 // have default arguments supplied in this or previous
691 // declarations. A default argument shall not be redefined
692 // by a later declaration (not even to the same value).
693 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000694 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000696 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000697 if (Param->isInvalidDecl())
698 /* We already complained about this parameter. */;
699 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000700 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000701 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000702 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000703 else
Mike Stump11289f42009-09-09 15:08:12 +0000704 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000705 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner199abbc2008-04-08 05:04:30 +0000707 LastMissingDefaultArg = p;
708 }
709 }
710
711 if (LastMissingDefaultArg > 0) {
712 // Some default arguments were missing. Clear out all of the
713 // default arguments up to (and including) the last missing
714 // default argument, so that we leave the function parameters
715 // in a semantically valid state.
716 for (p = 0; p <= LastMissingDefaultArg; ++p) {
717 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000718 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000720 }
721 }
722 }
723}
Douglas Gregor556877c2008-04-13 21:30:24 +0000724
Richard Smitheb3c10c2011-10-01 02:31:28 +0000725// CheckConstexprParameterTypes - Check whether a function's parameter types
726// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000727// diagnostic and return false.
728static bool CheckConstexprParameterTypes(Sema &SemaRef,
729 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000730 unsigned ArgIndex = 0;
731 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000732 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
733 e = FT->param_type_end();
734 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
736 SourceLocation ParamLoc = PD->getLocation();
737 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000738 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000739 diag::err_constexpr_non_literal_param,
740 ArgIndex+1, PD->getSourceRange(),
741 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000742 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000743 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000744 return true;
745}
746
747/// \brief Get diagnostic %select index for tag kind for
748/// record diagnostic message.
749/// WARNING: Indexes apply to particular diagnostics only!
750///
751/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000752static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000753 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000754 case TTK_Struct: return 0;
755 case TTK_Interface: return 1;
756 case TTK_Class: return 2;
757 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000758 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000759}
760
761// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
762// the requirements of a constexpr function definition or a constexpr
763// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000764// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000765//
Richard Smith3607ffe2012-02-13 03:54:03 +0000766// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
767bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
769 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000770 // C++11 [dcl.constexpr]p4:
771 // The definition of a constexpr constructor shall satisfy the following
772 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000774 const CXXRecordDecl *RD = MD->getParent();
775 if (RD->getNumVBases()) {
776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
777 << isa<CXXConstructorDecl>(NewFD)
778 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000779 for (const auto &I : RD->vbases())
780 Diag(I.getLocStart(),
781 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000782 return false;
783 }
Richard Smith7971b692012-01-13 04:54:00 +0000784 }
785
786 if (!isa<CXXConstructorDecl>(NewFD)) {
787 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000788 // The definition of a constexpr function shall satisfy the following
789 // constraints:
790 // - it shall not be virtual;
791 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
792 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000793 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794
Richard Smith3607ffe2012-02-13 03:54:03 +0000795 // If it's not obvious why this function is virtual, find an overridden
796 // function which uses the 'virtual' keyword.
797 const CXXMethodDecl *WrittenVirtual = Method;
798 while (!WrittenVirtual->isVirtualAsWritten())
799 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
800 if (WrittenVirtual != Method)
801 Diag(WrittenVirtual->getLocation(),
802 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 return false;
804 }
805
806 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000807 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000809 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000810 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000812 }
813
Richard Smith7971b692012-01-13 04:54:00 +0000814 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000815 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000816 return false;
817
Richard Smitheb3c10c2011-10-01 02:31:28 +0000818 return true;
819}
820
821/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000822/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823///
Richard Smithd9f663b2013-04-22 15:31:51 +0000824/// \return true if the body is OK (maybe only as an extension), false if we
825/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000827 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
828 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000829 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
830 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000831 for (const auto *DclIt : DS->decls()) {
832 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000833 case Decl::StaticAssert:
834 case Decl::Using:
835 case Decl::UsingShadow:
836 case Decl::UsingDirective:
837 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000838 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000839 // - static_assert-declarations
840 // - using-declarations,
841 // - using-directives,
842 continue;
843
844 case Decl::Typedef:
845 case Decl::TypeAlias: {
846 // - typedef declarations and alias-declarations that do not define
847 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000848 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000849 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
850 // Don't allow variably-modified types in constexpr functions.
851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
853 << TL.getSourceRange() << TL.getType()
854 << isa<CXXConstructorDecl>(Dcl);
855 return false;
856 }
857 continue;
858 }
859
860 case Decl::Enum:
861 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000862 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000863 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000865 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000866 ? diag::warn_cxx11_compat_constexpr_type_definition
867 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000868 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000869 continue;
870
Richard Smithd9f663b2013-04-22 15:31:51 +0000871 case Decl::EnumConstant:
872 case Decl::IndirectField:
873 case Decl::ParmVar:
874 // These can only appear with other declarations which are banned in
875 // C++11 and permitted in C++1y, so ignore them.
876 continue;
877
878 case Decl::Var: {
879 // C++1y [dcl.constexpr]p3 allows anything except:
880 // a definition of a variable of non-literal type or of static or
881 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000882 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000883 if (VD->isThisDeclarationADefinition()) {
884 if (VD->isStaticLocal()) {
885 SemaRef.Diag(VD->getLocation(),
886 diag::err_constexpr_local_var_static)
887 << isa<CXXConstructorDecl>(Dcl)
888 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
889 return false;
890 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000891 if (!VD->getType()->isDependentType() &&
892 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000893 VD->getLocation(), VD->getType(),
894 diag::err_constexpr_local_var_non_literal_type,
895 isa<CXXConstructorDecl>(Dcl)))
896 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000897 if (!VD->getType()->isDependentType() &&
898 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000899 SemaRef.Diag(VD->getLocation(),
900 diag::err_constexpr_local_var_no_init)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000906 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000907 ? diag::warn_cxx11_compat_constexpr_local_var
908 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000909 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000910 continue;
911 }
912
913 case Decl::NamespaceAlias:
914 case Decl::Function:
915 // These are disallowed in C++11 and permitted in C++1y. Allow them
916 // everywhere as an extension.
917 if (!Cxx1yLoc.isValid())
918 Cxx1yLoc = DS->getLocStart();
919 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000920
921 default:
922 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
923 << isa<CXXConstructorDecl>(Dcl);
924 return false;
925 }
926 }
927
928 return true;
929}
930
931/// Check that the given field is initialized within a constexpr constructor.
932///
933/// \param Dcl The constexpr constructor being checked.
934/// \param Field The field being checked. This may be a member of an anonymous
935/// struct or union nested within the class being checked.
936/// \param Inits All declarations, including anonymous struct/union members and
937/// indirect members, for which any initialization was provided.
938/// \param Diagnosed Set to true if an error is produced.
939static void CheckConstexprCtorInitializer(Sema &SemaRef,
940 const FunctionDecl *Dcl,
941 FieldDecl *Field,
942 llvm::SmallSet<Decl*, 16> &Inits,
943 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000944 if (Field->isInvalidDecl())
945 return;
946
Douglas Gregor556e5862011-10-10 17:22:13 +0000947 if (Field->isUnnamedBitfield())
948 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000949
Richard Smithab44d5b2013-12-10 08:25:00 +0000950 // Anonymous unions with no variant members and empty anonymous structs do not
951 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
952 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000953 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000954 (Field->getType()->isUnionType()
955 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
956 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000957 return;
958
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 if (!Inits.count(Field)) {
960 if (!Diagnosed) {
961 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
962 Diagnosed = true;
963 }
964 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
965 } else if (Field->isAnonymousStructOrUnion()) {
966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000967 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000968 // If an anonymous union contains an anonymous struct of which any member
969 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000970 if (!RD->isUnion() || Inits.count(I))
971 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000972 }
973}
974
Richard Smithd9f663b2013-04-22 15:31:51 +0000975/// Check the provided statement is allowed in a constexpr function
976/// definition.
977static bool
978CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000979 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000980 SourceLocation &Cxx1yLoc) {
981 // - its function-body shall be [...] a compound-statement that contains only
982 switch (S->getStmtClass()) {
983 case Stmt::NullStmtClass:
984 // - null statements,
985 return true;
986
987 case Stmt::DeclStmtClass:
988 // - static_assert-declarations
989 // - using-declarations,
990 // - using-directives,
991 // - typedef declarations and alias-declarations that do not define
992 // classes or enumerations,
993 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
994 return false;
995 return true;
996
997 case Stmt::ReturnStmtClass:
998 // - and exactly one return statement;
999 if (isa<CXXConstructorDecl>(Dcl)) {
1000 // C++1y allows return statements in constexpr constructors.
1001 if (!Cxx1yLoc.isValid())
1002 Cxx1yLoc = S->getLocStart();
1003 return true;
1004 }
1005
1006 ReturnStmts.push_back(S->getLocStart());
1007 return true;
1008
1009 case Stmt::CompoundStmtClass: {
1010 // C++1y allows compound-statements.
1011 if (!Cxx1yLoc.isValid())
1012 Cxx1yLoc = S->getLocStart();
1013
1014 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001015 for (auto *BodyIt : CompStmt->body()) {
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001017 Cxx1yLoc))
1018 return false;
1019 }
1020 return true;
1021 }
1022
1023 case Stmt::AttributedStmtClass:
1024 if (!Cxx1yLoc.isValid())
1025 Cxx1yLoc = S->getLocStart();
1026 return true;
1027
1028 case Stmt::IfStmtClass: {
1029 // C++1y allows if-statements.
1030 if (!Cxx1yLoc.isValid())
1031 Cxx1yLoc = S->getLocStart();
1032
1033 IfStmt *If = cast<IfStmt>(S);
1034 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1035 Cxx1yLoc))
1036 return false;
1037 if (If->getElse() &&
1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1039 Cxx1yLoc))
1040 return false;
1041 return true;
1042 }
1043
1044 case Stmt::WhileStmtClass:
1045 case Stmt::DoStmtClass:
1046 case Stmt::ForStmtClass:
1047 case Stmt::CXXForRangeStmtClass:
1048 case Stmt::ContinueStmtClass:
1049 // C++1y allows all of these. We don't allow them as extensions in C++11,
1050 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001051 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001052 break;
1053 if (!Cxx1yLoc.isValid())
1054 Cxx1yLoc = S->getLocStart();
1055 for (Stmt::child_range Children = S->children(); Children; ++Children)
1056 if (*Children &&
1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1058 Cxx1yLoc))
1059 return false;
1060 return true;
1061
1062 case Stmt::SwitchStmtClass:
1063 case Stmt::CaseStmtClass:
1064 case Stmt::DefaultStmtClass:
1065 case Stmt::BreakStmtClass:
1066 // C++1y allows switch-statements, and since they don't need variable
1067 // mutation, we can reasonably allow them in C++11 as an extension.
1068 if (!Cxx1yLoc.isValid())
1069 Cxx1yLoc = S->getLocStart();
1070 for (Stmt::child_range Children = S->children(); Children; ++Children)
1071 if (*Children &&
1072 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1073 Cxx1yLoc))
1074 return false;
1075 return true;
1076
1077 default:
1078 if (!isa<Expr>(S))
1079 break;
1080
1081 // C++1y allows expression-statements.
1082 if (!Cxx1yLoc.isValid())
1083 Cxx1yLoc = S->getLocStart();
1084 return true;
1085 }
1086
1087 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1088 << isa<CXXConstructorDecl>(Dcl);
1089 return false;
1090}
1091
Richard Smitheb3c10c2011-10-01 02:31:28 +00001092/// Check the body for the given constexpr function declaration only contains
1093/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1094///
1095/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001096bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001097 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001098 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001099 // The definition of a constexpr function shall satisfy the following
1100 // constraints: [...]
1101 // - its function-body shall be = delete, = default, or a
1102 // compound-statement
1103 //
Richard Smith74388b42012-02-04 00:33:54 +00001104 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001105 // In the definition of a constexpr constructor, [...]
1106 // - its function-body shall not be a function-try-block;
1107 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1108 << isa<CXXConstructorDecl>(Dcl);
1109 return false;
1110 }
1111
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001112 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001113
1114 // - its function-body shall be [...] a compound-statement that contains only
1115 // [... list of cases ...]
1116 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1117 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001118 for (auto *BodyIt : CompBody->body()) {
1119 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001120 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001121 }
1122
Richard Smithd9f663b2013-04-22 15:31:51 +00001123 if (Cxx1yLoc.isValid())
1124 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001125 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001126 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1127 : diag::ext_constexpr_body_invalid_stmt)
1128 << isa<CXXConstructorDecl>(Dcl);
1129
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 if (const CXXConstructorDecl *Constructor
1131 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1132 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001133 // DR1359:
1134 // - every non-variant non-static data member and base class sub-object
1135 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001136 // DR1460:
1137 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001138 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001139 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001140 if (Constructor->getNumCtorInitializers() == 0 &&
1141 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001142 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1143 return false;
1144 }
Richard Smithf368fb42011-10-10 16:38:04 +00001145 } else if (!Constructor->isDependentContext() &&
1146 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1148
1149 // Skip detailed checking if we have enough initializers, and we would
1150 // allow at most one initializer per member.
1151 bool AnyAnonStructUnionMembers = false;
1152 unsigned Fields = 0;
1153 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1154 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001155 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001156 AnyAnonStructUnionMembers = true;
1157 break;
1158 }
1159 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001160 // DR1460:
1161 // - if the class is a union-like class, but is not a union, for each of
1162 // its anonymous union members having variant members, exactly one of
1163 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001164 if (AnyAnonStructUnionMembers ||
1165 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1166 // Check initialization of non-static data members. Base classes are
1167 // always initialized so do not need to be checked. Dependent bases
1168 // might not have initializers in the member initializer list.
1169 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001170 for (const auto *I: Constructor->inits()) {
1171 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001172 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001173 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001174 Inits.insert(ID->chain_begin(), ID->chain_end());
1175 }
1176
1177 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001178 for (auto *I : RD->fields())
1179 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001180 if (Diagnosed)
1181 return false;
1182 }
1183 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 } else {
1185 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001186 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001187 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001188 // otherwise if there's no return statement, the function cannot
1189 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001190 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001191 (Dcl->getReturnType()->isVoidType() ||
1192 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001193 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001194 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1195 : diag::err_constexpr_body_no_return);
1196 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001197 }
1198 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001199 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001200 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1202 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1204 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001205 }
1206 }
1207
Richard Smith74388b42012-02-04 00:33:54 +00001208 // C++11 [dcl.constexpr]p5:
1209 // if no function argument values exist such that the function invocation
1210 // substitution would produce a constant expression, the program is
1211 // ill-formed; no diagnostic required.
1212 // C++11 [dcl.constexpr]p3:
1213 // - every constructor call and implicit conversion used in initializing the
1214 // return value shall be one of those allowed in a constant expression.
1215 // C++11 [dcl.constexpr]p4:
1216 // - every constructor involved in initializing non-static data members and
1217 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001218 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001219 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001220 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001221 << isa<CXXConstructorDecl>(Dcl);
1222 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1223 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001224 // Don't return false here: we allow this for compatibility in
1225 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001226 }
1227
Richard Smitheb3c10c2011-10-01 02:31:28 +00001228 return true;
1229}
1230
Douglas Gregor61956c42008-10-31 09:07:45 +00001231/// isCurrentClassName - Determine whether the identifier II is the
1232/// name of the class type currently being defined. In the case of
1233/// nested classes, this will only return true if II is the name of
1234/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001235bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1236 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001237 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001238
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001239 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001240 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001241 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001246 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001247 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001248 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001249}
1250
Richard Smithfb8b7b92013-10-15 00:00:26 +00001251/// \brief Determine whether the identifier II is a typo for the name of
1252/// the class type currently being defined. If so, update it to the identifier
1253/// that should have been used.
1254bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1255 assert(getLangOpts().CPlusPlus && "No class names in C!");
1256
1257 if (!getLangOpts().SpellChecking)
1258 return false;
1259
1260 CXXRecordDecl *CurDecl;
1261 if (SS && SS->isSet() && !SS->isInvalid()) {
1262 DeclContext *DC = computeDeclContext(*SS, true);
1263 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1264 } else
1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1266
1267 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1268 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1269 < II->getLength()) {
1270 II = CurDecl->getIdentifier();
1271 return true;
1272 }
1273
1274 return false;
1275}
1276
Douglas Gregordc974572012-11-10 07:24:09 +00001277/// \brief Determine whether the given class is a base class of the given
1278/// class, including looking at dependent bases.
1279static bool findCircularInheritance(const CXXRecordDecl *Class,
1280 const CXXRecordDecl *Current) {
1281 SmallVector<const CXXRecordDecl*, 8> Queue;
1282
1283 Class = Class->getCanonicalDecl();
1284 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001285 for (const auto &I : Current->bases()) {
1286 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001287 if (!Base)
1288 continue;
1289
1290 Base = Base->getDefinition();
1291 if (!Base)
1292 continue;
1293
1294 if (Base->getCanonicalDecl() == Class)
1295 return true;
1296
1297 Queue.push_back(Base);
1298 }
1299
1300 if (Queue.empty())
1301 return false;
1302
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001303 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001304 }
1305
1306 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001307}
1308
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001309/// \brief Perform propagation of DLL attributes from a derived class to a
1310/// templated base class for MS compatibility.
1311static void propagateDLLAttrToBaseClassTemplate(
1312 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1313 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1314 if (getDLLAttr(
1315 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1316 // If the base class template has a DLL attribute, don't try to change it.
1317 return;
1318 }
1319
1320 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1321 // If the base class is not already specialized, we can do the propagation.
1322 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1323 NewAttr->setInherited(true);
1324 BaseTemplateSpec->addAttr(NewAttr);
1325 return;
1326 }
1327
1328 bool DifferentAttribute = false;
1329 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1330 if (!SpecializationAttr->isInherited()) {
1331 // The template has previously been specialized or instantiated with an
1332 // explicit attribute. We should not try to change it.
1333 return;
1334 }
1335 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1336 // The specialization already has the right attribute.
1337 return;
1338 }
1339 DifferentAttribute = true;
1340 }
1341
1342 // The template was previously instantiated or explicitly specialized without
1343 // a dll attribute, or the template was previously instantiated with a
1344 // different inherited attribute. It's too late for us to change the
1345 // attribute, so warn that this is unsupported.
1346 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1347 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1348 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1349 if (BaseTemplateSpec->isExplicitSpecialization()) {
1350 S.Diag(BaseTemplateSpec->getLocation(),
1351 diag::note_template_class_explicit_specialization_was_here)
1352 << BaseTemplateSpec;
1353 } else {
1354 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1355 diag::note_template_class_instantiation_was_here)
1356 << BaseTemplateSpec;
1357 }
1358}
1359
Mike Stump11289f42009-09-09 15:08:12 +00001360/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001361///
1362/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1363/// and returns NULL otherwise.
1364CXXBaseSpecifier *
1365Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1366 SourceRange SpecifierRange,
1367 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001368 TypeSourceInfo *TInfo,
1369 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001370 QualType BaseType = TInfo->getType();
1371
Douglas Gregor463421d2009-03-03 04:44:36 +00001372 // C++ [class.union]p1:
1373 // A union shall not have base classes.
1374 if (Class->isUnion()) {
1375 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1376 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001377 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001378 }
1379
Douglas Gregor752a5952011-01-03 22:36:02 +00001380 if (EllipsisLoc.isValid() &&
1381 !TInfo->getType()->containsUnexpandedParameterPack()) {
1382 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1383 << TInfo->getTypeLoc().getSourceRange();
1384 EllipsisLoc = SourceLocation();
1385 }
Douglas Gregor62004702012-11-10 01:18:17 +00001386
1387 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1388
1389 if (BaseType->isDependentType()) {
1390 // Make sure that we don't have circular inheritance among our dependent
1391 // bases. For non-dependent bases, the check for completeness below handles
1392 // this.
1393 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1394 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1395 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001396 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001397 Diag(BaseLoc, diag::err_circular_inheritance)
1398 << BaseType << Context.getTypeDeclType(Class);
1399
1400 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1401 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1402 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001403
1404 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001405 }
1406 }
1407
Mike Stump11289f42009-09-09 15:08:12 +00001408 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001409 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001410 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001411 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001412
1413 // Base specifiers must be record types.
1414 if (!BaseType->isRecordType()) {
1415 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001416 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001417 }
1418
1419 // C++ [class.union]p1:
1420 // A union shall not be used as a base class.
1421 if (BaseType->isUnionType()) {
1422 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001423 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001424 }
1425
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001426 // For the MS ABI, propagate DLL attributes to base class templates.
1427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1428 if (Attr *ClassAttr = getDLLAttr(Class)) {
1429 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1430 BaseType->getAsCXXRecordDecl())) {
1431 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1432 BaseTemplate, BaseLoc);
1433 }
1434 }
1435 }
1436
Douglas Gregor463421d2009-03-03 04:44:36 +00001437 // C++ [class.derived]p2:
1438 // The class-name in a base-specifier shall not be an incompletely
1439 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001440 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001441 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001442 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001443 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001444 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001445
Eli Friedmanc96d4962009-08-15 21:55:26 +00001446 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001447 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001448 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001449 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001450 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001451 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001452 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001453
David Majnemer9b1754d2013-11-02 12:00:36 +00001454 // A class which contains a flexible array member is not suitable for use as a
1455 // base class:
1456 // - If the layout determines that a base comes before another base,
1457 // the flexible array member would index into the subsequent base.
1458 // - If the layout determines that base comes before the derived class,
1459 // the flexible array member would index into the derived class.
1460 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1461 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1462 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001464 }
1465
Anders Carlsson65c76d32011-03-25 14:55:14 +00001466 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001467 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001468 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001469 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001470 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001471 << CXXBaseDecl->getDeclName()
1472 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001473 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1474 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001475 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001476 }
1477
John McCall3696dcb2010-08-17 07:23:57 +00001478 if (BaseDecl->isInvalidDecl())
1479 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001480
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001481 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001482 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001483 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001484 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001485}
1486
Douglas Gregor556877c2008-04-13 21:30:24 +00001487/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1488/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001489/// example:
1490/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001491/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001492BaseResult
John McCall48871652010-08-21 09:40:31 +00001493Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001494 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001495 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001496 ParsedType basetype, SourceLocation BaseLoc,
1497 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001498 if (!classdecl)
1499 return true;
1500
Douglas Gregorc40290e2009-03-09 23:48:35 +00001501 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001502 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001503 if (!Class)
1504 return true;
1505
David Majnemer5ef4fe72014-06-13 06:43:46 +00001506 // We haven't yet attached the base specifiers.
1507 Class->setIsParsingBaseSpecifiers();
1508
Richard Smith4c96e992013-02-19 23:47:15 +00001509 // We do not support any C++11 attributes on base-specifiers yet.
1510 // Diagnose any attributes we see.
1511 if (!Attributes.empty()) {
1512 for (AttributeList *Attr = Attributes.getList(); Attr;
1513 Attr = Attr->getNext()) {
1514 if (Attr->isInvalid() ||
1515 Attr->getKind() == AttributeList::IgnoredAttribute)
1516 continue;
1517 Diag(Attr->getLoc(),
1518 Attr->getKind() == AttributeList::UnknownAttribute
1519 ? diag::warn_unknown_attribute_ignored
1520 : diag::err_base_specifier_attribute)
1521 << Attr->getName();
1522 }
1523 }
1524
Craig Topperc3ec1492014-05-26 06:22:03 +00001525 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001526 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001527
Douglas Gregor752a5952011-01-03 22:36:02 +00001528 if (EllipsisLoc.isInvalid() &&
1529 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001530 UPPC_BaseType))
1531 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001532
Douglas Gregor463421d2009-03-03 04:44:36 +00001533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001534 Virtual, Access, TInfo,
1535 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001536 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001537 else
1538 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregor463421d2009-03-03 04:44:36 +00001540 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001541}
Douglas Gregor556877c2008-04-13 21:30:24 +00001542
Douglas Gregor463421d2009-03-03 04:44:36 +00001543/// \brief Performs the actual work of attaching the given base class
1544/// specifiers to a C++ class.
1545bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1546 unsigned NumBases) {
1547 if (NumBases == 0)
1548 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001549
1550 // Used to keep track of which base types we have already seen, so
1551 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001552 // that the key is always the unqualified canonical type of the base
1553 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001554 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1555
1556 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001557 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001558 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001559 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001560 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001561 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001562 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001563
1564 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1565 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001566 // C++ [class.mi]p3:
1567 // A class shall not be specified as a direct base class of a
1568 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001569 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001570 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001571 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001572 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001573
1574 // Delete the duplicate base class specifier; we're going to
1575 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001576 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001577
1578 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001579 } else {
1580 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001581 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001582 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001583 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1585 if (Class->isInterface() &&
1586 (!RD->isInterface() ||
1587 KnownBase->getAccessSpecifier() != AS_public)) {
1588 // The Microsoft extension __interface does not permit bases that
1589 // are not themselves public interfaces.
1590 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1591 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1592 << RD->getSourceRange();
1593 Invalid = true;
1594 }
1595 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001596 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001597 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001598 }
1599 }
1600
1601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001603
1604 // Delete the remaining (good) base class specifiers, since their
1605 // data has been copied into the CXXRecordDecl.
1606 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001607 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001608
1609 return Invalid;
1610}
1611
1612/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1613/// class, after checking whether there are any duplicate base
1614/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001616 unsigned NumBases) {
1617 if (!ClassDecl || !Bases || !NumBases)
1618 return;
1619
1620 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001622}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001623
Douglas Gregor36d1b142009-10-06 17:59:45 +00001624/// \brief Determine whether the type \p Derived is a C++ class that is
1625/// derived from the type \p Base.
1626bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001627 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001628 return false;
John McCalle78aac42010-03-10 03:28:59 +00001629
Douglas Gregor45bb4832013-03-26 23:36:30 +00001630 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001631 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001632 return false;
1633
Douglas Gregor45bb4832013-03-26 23:36:30 +00001634 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001635 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001636 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001637
1638 // If either the base or the derived type is invalid, don't try to
1639 // check whether one is derived from the other.
1640 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1641 return false;
1642
John McCall67da35c2010-02-04 22:26:26 +00001643 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1644 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001645}
1646
1647/// \brief Determine whether the type \p Derived is a C++ class that is
1648/// derived from the type \p Base.
1649bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001650 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001651 return false;
1652
Douglas Gregor45bb4832013-03-26 23:36:30 +00001653 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001654 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001655 return false;
1656
Douglas Gregor45bb4832013-03-26 23:36:30 +00001657 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001658 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001659 return false;
1660
Douglas Gregor36d1b142009-10-06 17:59:45 +00001661 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1662}
1663
Anders Carlssona70cff62010-04-24 19:06:50 +00001664void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001665 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001666 assert(BasePathArray.empty() && "Base path array must be empty!");
1667 assert(Paths.isRecordingPaths() && "Must record paths!");
1668
1669 const CXXBasePath &Path = Paths.front();
1670
1671 // We first go backward and check if we have a virtual base.
1672 // FIXME: It would be better if CXXBasePath had the base specifier for
1673 // the nearest virtual base.
1674 unsigned Start = 0;
1675 for (unsigned I = Path.size(); I != 0; --I) {
1676 if (Path[I - 1].Base->isVirtual()) {
1677 Start = I - 1;
1678 break;
1679 }
1680 }
1681
1682 // Now add all bases.
1683 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001684 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001685}
1686
Douglas Gregor88d292c2010-05-13 16:44:06 +00001687/// \brief Determine whether the given base path includes a virtual
1688/// base class.
John McCallcf142162010-08-07 06:22:56 +00001689bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1690 for (CXXCastPath::const_iterator B = BasePath.begin(),
1691 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001692 B != BEnd; ++B)
1693 if ((*B)->isVirtual())
1694 return true;
1695
1696 return false;
1697}
1698
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1700/// conversion (where Derived and Base are class types) is
1701/// well-formed, meaning that the conversion is unambiguous (and
1702/// that all of the base classes are accessible). Returns true
1703/// and emits a diagnostic if the code is ill-formed, returns false
1704/// otherwise. Loc is the location where this routine should point to
1705/// if there is an error, and Range is the source range to highlight
1706/// if there is an error.
1707bool
1708Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001709 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001710 unsigned AmbigiousBaseConvID,
1711 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001712 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001713 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001714 // First, determine whether the path from Derived to Base is
1715 // ambiguous. This is slightly more expensive than checking whether
1716 // the Derived to Base conversion exists, because here we need to
1717 // explore multiple paths to determine if there is an ambiguity.
1718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1719 /*DetectVirtual=*/false);
1720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1721 assert(DerivationOkay &&
1722 "Can only be used with a derived-to-base conversion");
1723 (void)DerivationOkay;
1724
1725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001726 if (InaccessibleBaseID) {
1727 // Check that the base class can be accessed.
1728 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1729 InaccessibleBaseID)) {
1730 case AR_inaccessible:
1731 return true;
1732 case AR_accessible:
1733 case AR_dependent:
1734 case AR_delayed:
1735 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001736 }
John McCall5b0829a2010-02-10 09:31:12 +00001737 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001738
1739 // Build a base path if necessary.
1740 if (BasePath)
1741 BuildBasePathArray(Paths, *BasePath);
1742 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001743 }
1744
David Majnemer626032f2013-06-22 06:43:58 +00001745 if (AmbigiousBaseConvID) {
1746 // We know that the derived-to-base conversion is ambiguous, and
1747 // we're going to produce a diagnostic. Perform the derived-to-base
1748 // search just one more time to compute all of the possible paths so
1749 // that we can print them out. This is more expensive than any of
1750 // the previous derived-to-base checks we've done, but at this point
1751 // performance isn't as much of an issue.
1752 Paths.clear();
1753 Paths.setRecordingPaths(true);
1754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1755 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1756 (void)StillOkay;
1757
1758 // Build up a textual representation of the ambiguous paths, e.g.,
1759 // D -> B -> A, that will be used to illustrate the ambiguous
1760 // conversions in the diagnostic. We only print one of the paths
1761 // to each base class subobject.
1762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1763
1764 Diag(Loc, AmbigiousBaseConvID)
1765 << Derived << Base << PathDisplayStr << Range << Name;
1766 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001767 return true;
1768}
1769
1770bool
1771Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001772 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001773 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001774 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001775 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001776 IgnoreAccess ? 0
1777 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001778 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001779 Loc, Range, DeclarationName(),
1780 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001781}
1782
1783
1784/// @brief Builds a string representing ambiguous paths from a
1785/// specific derived class to different subobjects of the same base
1786/// class.
1787///
1788/// This function builds a string that can be used in error messages
1789/// to show the different paths that one can take through the
1790/// inheritance hierarchy to go from the derived class to different
1791/// subobjects of a base class. The result looks something like this:
1792/// @code
1793/// struct D -> struct B -> struct A
1794/// struct D -> struct C -> struct A
1795/// @endcode
1796std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1797 std::string PathDisplayStr;
1798 std::set<unsigned> DisplayedPaths;
1799 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1800 Path != Paths.end(); ++Path) {
1801 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1802 // We haven't displayed a path to this particular base
1803 // class subobject yet.
1804 PathDisplayStr += "\n ";
1805 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1806 for (CXXBasePath::const_iterator Element = Path->begin();
1807 Element != Path->end(); ++Element)
1808 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1809 }
1810 }
1811
1812 return PathDisplayStr;
1813}
1814
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001815//===----------------------------------------------------------------------===//
1816// C++ class member Handling
1817//===----------------------------------------------------------------------===//
1818
Abramo Bagnarad7340582010-06-05 05:09:32 +00001819/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001820bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1821 SourceLocation ASLoc,
1822 SourceLocation ColonLoc,
1823 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001824 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001825 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001826 ASLoc, ColonLoc);
1827 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001828 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001829}
1830
Richard Smith18f07db2012-08-06 03:25:17 +00001831/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001832void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001833 if (D->isInvalidDecl())
1834 return;
1835
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001836 // We only care about "override" and "final" declarations.
1837 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1838 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001839
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001841
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001842 // We can't check dependent instance methods.
1843 if (MD && MD->isInstance() &&
1844 (MD->getParent()->hasAnyDependentBases() ||
1845 MD->getType()->isDependentType()))
1846 return;
1847
1848 if (MD && !MD->isVirtual()) {
1849 // If we have a non-virtual method, check if if hides a virtual method.
1850 // (In that case, it's most likely the method has the wrong type.)
1851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1852 FindHiddenVirtualMethods(MD, OverloadedMethods);
1853
1854 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001855 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1856 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001857 diag::override_keyword_hides_virtual_member_function)
1858 << "override" << (OverloadedMethods.size() > 1);
1859 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001860 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001861 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001862 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1863 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001864 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001865 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1866 MD->setInvalidDecl();
1867 return;
1868 }
1869 // Fall through into the general case diagnostic.
1870 // FIXME: We might want to attempt typo correction here.
1871 }
1872
1873 if (!MD || !MD->isVirtual()) {
1874 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1875 Diag(OA->getLocation(),
1876 diag::override_keyword_only_allowed_on_virtual_member_functions)
1877 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1878 D->dropAttr<OverrideAttr>();
1879 }
1880 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1881 Diag(FA->getLocation(),
1882 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001883 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1884 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001885 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001886 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001887 return;
1888 }
Richard Smith18f07db2012-08-06 03:25:17 +00001889
Richard Smith18f07db2012-08-06 03:25:17 +00001890 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001891 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001892 // does not override a member function of a base class, the program is
1893 // ill-formed.
1894 bool HasOverriddenMethods =
1895 MD->begin_overridden_methods() != MD->end_overridden_methods();
1896 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1897 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1898 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001899}
1900
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001901void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1902 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1903 return;
1904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1905 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1906 isa<CXXDestructorDecl>(MD))
1907 return;
1908
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001909 SourceLocation Loc = MD->getLocation();
1910 SourceLocation SpellingLoc = Loc;
1911 if (getSourceManager().isMacroArgExpansion(Loc))
1912 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1913 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1914 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001915 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001916
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001917 if (MD->size_overridden_methods() > 0) {
1918 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1919 << MD->getDeclName();
1920 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1921 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1922 }
1923}
1924
Richard Smith18f07db2012-08-06 03:25:17 +00001925/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001926/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001927/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001928bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1929 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001930 FinalAttr *FA = Old->getAttr<FinalAttr>();
1931 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001932 return false;
1933
1934 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001935 << New->getDeclName()
1936 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001937 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1938 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001939}
1940
Daniel Jasper0baec5492012-06-06 08:32:04 +00001941static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001942 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1943 // FIXME: Destruction of ObjC lifetime types has side-effects.
1944 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1945 return !RD->isCompleteDefinition() ||
1946 !RD->hasTrivialDefaultConstructor() ||
1947 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001948 return false;
1949}
1950
John McCall5e77d762013-04-16 07:28:30 +00001951static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001953 if (it->isDeclspecPropertyAttribute())
1954 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001955 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001956}
1957
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001958/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1959/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001960/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001961/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1962/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001963NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001964Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001965 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001966 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001967 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001968 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1970 DeclarationName Name = NameInfo.getName();
1971 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001972
1973 // For anonymous bitfields, the location should point to the type.
1974 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001975 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001976
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001977 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001978
John McCallb1cd7da2010-06-04 08:34:12 +00001979 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001980 assert(!DS.isFriendSpecified());
1981
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001982 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001983
John McCalldb632ac2012-09-25 07:32:39 +00001984 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1985 // The Microsoft extension __interface only permits public member functions
1986 // and prohibits constructors, destructors, operators, non-public member
1987 // functions, static methods and data members.
1988 unsigned InvalidDecl;
1989 bool ShowDeclName = true;
1990 if (!isFunc)
1991 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1992 else if (AS != AS_public)
1993 InvalidDecl = 2;
1994 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1995 InvalidDecl = 3;
1996 else switch (Name.getNameKind()) {
1997 case DeclarationName::CXXConstructorName:
1998 InvalidDecl = 4;
1999 ShowDeclName = false;
2000 break;
2001
2002 case DeclarationName::CXXDestructorName:
2003 InvalidDecl = 5;
2004 ShowDeclName = false;
2005 break;
2006
2007 case DeclarationName::CXXOperatorName:
2008 case DeclarationName::CXXConversionFunctionName:
2009 InvalidDecl = 6;
2010 break;
2011
2012 default:
2013 InvalidDecl = 0;
2014 break;
2015 }
2016
2017 if (InvalidDecl) {
2018 if (ShowDeclName)
2019 Diag(Loc, diag::err_invalid_member_in_interface)
2020 << (InvalidDecl-1) << Name;
2021 else
2022 Diag(Loc, diag::err_invalid_member_in_interface)
2023 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002024 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002025 }
2026 }
2027
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002028 // C++ 9.2p6: A member shall not be declared to have automatic storage
2029 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002030 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2031 // data members and cannot be applied to names declared const or static,
2032 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002033 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002034 case DeclSpec::SCS_unspecified:
2035 case DeclSpec::SCS_typedef:
2036 case DeclSpec::SCS_static:
2037 break;
2038 case DeclSpec::SCS_mutable:
2039 if (isFunc) {
2040 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002041
Richard Smithb4a9e862013-04-12 22:46:28 +00002042 // FIXME: It would be nicer if the keyword was ignored only for this
2043 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002044 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002045 }
2046 break;
2047 default:
2048 Diag(DS.getStorageClassSpecLoc(),
2049 diag::err_storageclass_invalid_for_member);
2050 D.getMutableDeclSpec().ClearStorageClassSpecs();
2051 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002052 }
2053
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002054 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2055 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002056 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002057
David Blaikie35506f82013-01-30 01:22:18 +00002058 if (DS.isConstexprSpecified() && isInstField) {
2059 SemaDiagnosticBuilder B =
2060 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2061 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2062 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002063 B << 0 << 0;
2064 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2065 B << FixItHint::CreateRemoval(ConstexprLoc);
2066 else {
2067 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2068 D.getMutableDeclSpec().ClearConstexprSpec();
2069 const char *PrevSpec;
2070 unsigned DiagID;
2071 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2072 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2073 (void)Failed;
2074 assert(!Failed && "Making a constexpr member const shouldn't fail");
2075 }
David Blaikie35506f82013-01-30 01:22:18 +00002076 } else {
2077 B << 1;
2078 const char *PrevSpec;
2079 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002080 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002081 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2082 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002084 "This is the only DeclSpec that should fail to be applied");
2085 B << 1;
2086 } else {
2087 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2088 isInstField = false;
2089 }
2090 }
2091 }
2092
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002093 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002094 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002095 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002096
2097 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002098 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002099 Diag(Loc, diag::err_bad_variable_name)
2100 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002101 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002102 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002103
Benjamin Kramer365082d2012-05-19 16:34:46 +00002104 IdentifierInfo *II = Name.getAsIdentifierInfo();
2105
Douglas Gregor7c26c042011-09-21 14:40:46 +00002106 // Member field could not be with "template" keyword.
2107 // So TemplateParameterLists should be empty in this case.
2108 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002109 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002110 if (TemplateParams->size()) {
2111 // There is no such thing as a member field template.
2112 Diag(D.getIdentifierLoc(), diag::err_template_member)
2113 << II
2114 << SourceRange(TemplateParams->getTemplateLoc(),
2115 TemplateParams->getRAngleLoc());
2116 } else {
2117 // There is an extraneous 'template<>' for this member.
2118 Diag(TemplateParams->getTemplateLoc(),
2119 diag::err_template_member_noparams)
2120 << II
2121 << SourceRange(TemplateParams->getTemplateLoc(),
2122 TemplateParams->getRAngleLoc());
2123 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002124 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002125 }
2126
Douglas Gregora007d362010-10-13 22:19:53 +00002127 if (SS.isSet() && !SS.isInvalid()) {
2128 // The user provided a superfluous scope specifier inside a class
2129 // definition:
2130 //
2131 // class X {
2132 // int X::member;
2133 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002134 if (DeclContext *DC = computeDeclContext(SS, false))
2135 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002136 else
2137 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2138 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002139
Douglas Gregora007d362010-10-13 22:19:53 +00002140 SS.clear();
2141 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002142
John McCall5e77d762013-04-16 07:28:30 +00002143 AttributeList *MSPropertyAttr =
2144 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002145 if (MSPropertyAttr) {
2146 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2147 BitWidth, InitStyle, AS, MSPropertyAttr);
2148 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002149 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002150 isInstField = false;
2151 } else {
2152 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2153 BitWidth, InitStyle, AS);
2154 assert(Member && "HandleField never returns null");
2155 }
2156 } else {
2157 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2158
2159 Member = HandleDeclarator(S, D, TemplateParameterLists);
2160 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002161 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002162
2163 // Non-instance-fields can't have a bitfield.
2164 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002165 if (Member->isInvalidDecl()) {
2166 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002167 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002168 // C++ 9.6p3: A bit-field shall not be a static member.
2169 // "static member 'A' cannot be a bit-field"
2170 Diag(Loc, diag::err_static_not_bitfield)
2171 << Name << BitWidth->getSourceRange();
2172 } else if (isa<TypedefDecl>(Member)) {
2173 // "typedef member 'x' cannot be a bit-field"
2174 Diag(Loc, diag::err_typedef_not_bitfield)
2175 << Name << BitWidth->getSourceRange();
2176 } else {
2177 // A function typedef ("typedef int f(); f a;").
2178 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2179 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002180 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002181 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Craig Topperc3ec1492014-05-26 06:22:03 +00002184 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002185 Member->setInvalidDecl();
2186 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002187
2188 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002189
Larisse Voufo39a1e502013-08-06 01:03:05 +00002190 // If we have declared a member function template or static data member
2191 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002192 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2193 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002194 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2195 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002196 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002197
Richard Smith18f07db2012-08-06 03:25:17 +00002198 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002199 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002200 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002201 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2202 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002203
Douglas Gregorf2f08062011-03-08 17:10:18 +00002204 if (VS.getLastLocation().isValid()) {
2205 // Update the end location of a method that has a virt-specifiers.
2206 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2207 MD->setRangeEnd(VS.getLastLocation());
2208 }
Richard Smith18f07db2012-08-06 03:25:17 +00002209
Anders Carlssonc87f8612011-01-20 06:29:02 +00002210 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002211
Douglas Gregor92751d42008-11-17 22:58:34 +00002212 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002213
Daniel Jasper0baec5492012-06-06 08:32:04 +00002214 if (isInstField) {
2215 FieldDecl *FD = cast<FieldDecl>(Member);
2216 FieldCollector->Add(FD);
2217
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002218 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002219 // Remember all explicit private FieldDecls that have a name, no side
2220 // effects and are not part of a dependent type declaration.
2221 if (!FD->isImplicit() && FD->getDeclName() &&
2222 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002223 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002224 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002225 !InitializationHasSideEffects(*FD))
2226 UnusedPrivateFields.insert(FD);
2227 }
2228 }
2229
John McCall48871652010-08-21 09:40:31 +00002230 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002231}
2232
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002233namespace {
2234 class UninitializedFieldVisitor
2235 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2236 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002237 // List of Decls to generate a warning on. Also remove Decls that become
2238 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002239 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002240 // List of base classes of the record. Classes are removed after their
2241 // initializers.
2242 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002243 // Vector of decls to be removed from the Decl set prior to visiting the
2244 // nodes. These Decls may have been initialized in the prior initializer.
2245 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002246 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002247 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002248 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002249 // InitList is true, special case initialization of FieldDecls matching
2250 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002251 bool InitList;
2252 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002253 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2254
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002255 public:
2256 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002257 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002258 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2259 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2260 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2261 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002262
Richard Trieufa1d0a72014-10-17 20:56:10 +00002263 // Returns true if the use of ME is not an uninitialized use.
2264 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2265 bool CheckReferenceOnly) {
2266 llvm::SmallVector<FieldDecl*, 4> Fields;
2267 bool ReferenceField = false;
2268 while (ME) {
2269 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2270 if (!FD)
2271 return false;
2272 Fields.push_back(FD);
2273 if (FD->getType()->isReferenceType())
2274 ReferenceField = true;
2275 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2276 }
2277
2278 // Binding a reference to an unintialized field is not an
2279 // uninitialized use.
2280 if (CheckReferenceOnly && !ReferenceField)
2281 return true;
2282
2283 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2284 // Discard the first field since it is the field decl that is being
2285 // initialized.
2286 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2287 UsedFieldIndex.push_back((*I)->getFieldIndex());
2288 }
2289
2290 for (auto UsedIter = UsedFieldIndex.begin(),
2291 UsedEnd = UsedFieldIndex.end(),
2292 OrigIter = InitFieldIndex.begin(),
2293 OrigEnd = InitFieldIndex.end();
2294 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2295 if (*UsedIter < *OrigIter)
2296 return true;
2297 if (*UsedIter > *OrigIter)
2298 break;
2299 }
2300
2301 return false;
2302 }
2303
Richard Trieu2d779b92014-10-01 03:44:58 +00002304 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2305 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002306 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2307 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002308
Richard Trieu1bc22c12013-09-13 03:20:53 +00002309 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2310 // or union.
2311 MemberExpr *FieldME = ME;
2312
Richard Trieu2d779b92014-10-01 03:44:58 +00002313 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2314
Richard Trieu1bc22c12013-09-13 03:20:53 +00002315 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002316 while (MemberExpr *SubME =
2317 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002318
Richard Trieufa1d0a72014-10-17 20:56:10 +00002319 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002320 return;
2321
Richard Trieufa1d0a72014-10-17 20:56:10 +00002322 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002323 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002324 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002325
Richard Trieu2d779b92014-10-01 03:44:58 +00002326 if (!FieldME->getType().isPODType(S.Context))
2327 AllPODFields = false;
2328
Richard Trieu3630c392014-11-21 03:10:30 +00002329 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002330 }
2331
Richard Trieu3630c392014-11-21 03:10:30 +00002332 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002333 return;
2334
Richard Trieu2d779b92014-10-01 03:44:58 +00002335 if (AddressOf && AllPODFields)
2336 return;
2337
Richard Trieu406e65c2013-09-20 03:03:06 +00002338 ValueDecl* FoundVD = FieldME->getMemberDecl();
2339
Richard Trieu3630c392014-11-21 03:10:30 +00002340 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2341 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2342 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2343 }
2344
2345 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2346 QualType T = BaseCast->getType();
2347 if (T->isPointerType() &&
2348 BaseClasses.count(T->getPointeeType())) {
2349 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2350 << T->getPointeeType() << FoundVD;
2351 }
2352 }
2353 }
2354
Richard Trieuef64e942013-10-25 00:56:00 +00002355 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002356 return;
2357
Richard Trieuef64e942013-10-25 00:56:00 +00002358 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002359
Richard Trieufa1d0a72014-10-17 20:56:10 +00002360 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2361 // Special checking for initializer lists.
2362 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2363 return;
2364 }
2365 } else {
2366 // Prevent double warnings on use of unbounded references.
2367 if (CheckReferenceOnly && !IsReference)
2368 return;
2369 }
Richard Trieuef64e942013-10-25 00:56:00 +00002370
2371 unsigned diag = IsReference
2372 ? diag::warn_reference_field_is_uninit
2373 : diag::warn_field_is_uninit;
2374 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2375 if (Constructor)
2376 S.Diag(Constructor->getLocation(),
2377 diag::note_uninit_in_this_constructor)
2378 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2379
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002380 }
2381
Richard Trieu2d779b92014-10-01 03:44:58 +00002382 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002383 E = E->IgnoreParens();
2384
2385 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002386 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2387 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002388 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002389 }
2390
2391 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002392 Visit(CO->getCond());
2393 HandleValue(CO->getTrueExpr(), AddressOf);
2394 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002395 return;
2396 }
2397
2398 if (BinaryConditionalOperator *BCO =
2399 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002400 Visit(BCO->getCond());
2401 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002402 return;
2403 }
2404
Richard Trieuabf6ec42014-08-27 22:15:10 +00002405 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002406 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002407 return;
2408 }
2409
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2411 switch (BO->getOpcode()) {
2412 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002413 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002414 case(BO_PtrMemD):
2415 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002416 HandleValue(BO->getLHS(), AddressOf);
2417 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002418 return;
2419 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002420 Visit(BO->getLHS());
2421 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002422 return;
2423 }
2424 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002425
2426 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002427 }
2428
Richard Trieufa1d0a72014-10-17 20:56:10 +00002429 void CheckInitListExpr(InitListExpr *ILE) {
2430 InitFieldIndex.push_back(0);
2431 for (auto Child : ILE->children()) {
2432 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2433 CheckInitListExpr(SubList);
2434 } else {
2435 Visit(Child);
2436 }
2437 ++InitFieldIndex.back();
2438 }
2439 InitFieldIndex.pop_back();
2440 }
2441
Richard Trieu8d08a272014-08-28 03:23:47 +00002442 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002443 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002444 // Remove Decls that may have been initialized in the previous
2445 // initializer.
2446 for (ValueDecl* VD : DeclsToRemove)
2447 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002448 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002449
Richard Trieu8d08a272014-08-28 03:23:47 +00002450 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002451 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2452
2453 if (ILE && Field) {
2454 InitList = true;
2455 InitListFieldDecl = Field;
2456 InitFieldIndex.clear();
2457 CheckInitListExpr(ILE);
2458 } else {
2459 InitList = false;
2460 Visit(E);
2461 }
2462
Richard Trieu8d08a272014-08-28 03:23:47 +00002463 if (Field)
2464 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002465 if (BaseClass)
2466 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002467 }
2468
Richard Trieu1bc22c12013-09-13 03:20:53 +00002469 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002470 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002471 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002472 }
2473
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002474 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002475 if (E->getCastKind() == CK_LValueToRValue) {
2476 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2477 return;
2478 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002479
2480 Inherited::VisitImplicitCastExpr(E);
2481 }
2482
Richard Trieu1bc22c12013-09-13 03:20:53 +00002483 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002484 if (E->getConstructor()->isCopyConstructor()) {
2485 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002486 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2487 if (ILE->getNumInits() == 1)
2488 ArgExpr = ILE->getInit(0);
2489 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2490 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002491 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002492 HandleValue(ArgExpr, false /*AddressOf*/);
2493 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002494 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002495 Inherited::VisitCXXConstructExpr(E);
2496 }
2497
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002498 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2499 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002500 if (isa<MemberExpr>(Callee)) {
2501 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002502 for (auto Arg : E->arguments())
2503 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002504 return;
2505 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002506
2507 Inherited::VisitCXXMemberCallExpr(E);
2508 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002509
Richard Trieu11fd0792014-08-26 04:30:55 +00002510 void VisitCallExpr(CallExpr *E) {
2511 // Treat std::move as a use.
2512 if (E->getNumArgs() == 1) {
2513 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002514 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2515 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002516 HandleValue(E->getArg(0), false /*AddressOf*/);
2517 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002518 }
2519 }
2520 }
2521
2522 Inherited::VisitCallExpr(E);
2523 }
2524
Richard Trieud4a01362014-10-31 21:10:22 +00002525 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2526 Expr *Callee = E->getCallee();
2527
2528 if (isa<UnresolvedLookupExpr>(Callee))
2529 return Inherited::VisitCXXOperatorCallExpr(E);
2530
2531 Visit(Callee);
2532 for (auto Arg : E->arguments())
2533 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2534 }
2535
Richard Trieu406e65c2013-09-20 03:03:06 +00002536 void VisitBinaryOperator(BinaryOperator *E) {
2537 // If a field assignment is detected, remove the field from the
2538 // uninitiailized field set.
2539 if (E->getOpcode() == BO_Assign)
2540 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2541 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002542 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002543 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002544
Richard Trieu52b8b602014-09-25 01:15:40 +00002545 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002546 HandleValue(E->getLHS(), false /*AddressOf*/);
2547 Visit(E->getRHS());
2548 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002549 }
2550
Richard Trieu406e65c2013-09-20 03:03:06 +00002551 Inherited::VisitBinaryOperator(E);
2552 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002553
2554 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002555 if (E->isIncrementDecrementOp()) {
2556 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2557 return;
2558 }
2559 if (E->getOpcode() == UO_AddrOf) {
2560 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2561 HandleValue(ME->getBase(), true /*AddressOf*/);
2562 return;
2563 }
2564 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002565
2566 Inherited::VisitUnaryOperator(E);
2567 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002568 };
Richard Trieuef64e942013-10-25 00:56:00 +00002569
2570 // Diagnose value-uses of fields to initialize themselves, e.g.
2571 // foo(foo)
2572 // where foo is not also a parameter to the constructor.
2573 // Also diagnose across field uninitialized use such as
2574 // x(y), y(x)
2575 // TODO: implement -Wuninitialized and fold this into that framework.
2576 static void DiagnoseUninitializedFields(
2577 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2578
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002579 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2580 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002581 return;
2582 }
2583
2584 if (Constructor->isInvalidDecl())
2585 return;
2586
2587 const CXXRecordDecl *RD = Constructor->getParent();
2588
Richard Trieu353a4b42014-10-22 05:21:59 +00002589 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002590 return;
2591
Richard Trieuef64e942013-10-25 00:56:00 +00002592 // Holds fields that are uninitialized.
2593 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2594
2595 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002596 for (auto *I : RD->decls()) {
2597 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002598 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002599 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002600 UninitializedFields.insert(IFD->getAnonField());
2601 }
2602 }
2603
Richard Trieu3630c392014-11-21 03:10:30 +00002604 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2605 for (auto I : RD->bases())
2606 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2607
2608 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002609 return;
2610
2611 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002612 UninitializedFields,
2613 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002614
Aaron Ballman0ad78302014-03-13 17:34:31 +00002615 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002616 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002617 break;
2618
Aaron Ballman0ad78302014-03-13 17:34:31 +00002619 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002620 if (!InitExpr)
2621 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002622
Richard Trieu8d08a272014-08-28 03:23:47 +00002623 if (CXXDefaultInitExpr *Default =
2624 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2625 InitExpr = Default->getExpr();
2626 if (!InitExpr)
2627 continue;
2628 // In class initializers will point to the constructor.
2629 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002630 FieldInit->getAnyMember(),
2631 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002632 } else {
2633 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002634 FieldInit->getAnyMember(),
2635 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002636 }
Richard Trieuef64e942013-10-25 00:56:00 +00002637 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002638 }
2639} // namespace
2640
Richard Smith74108172014-01-17 03:11:34 +00002641/// \brief Enter a new C++ default initializer scope. After calling this, the
2642/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2643/// parsing or instantiating the initializer failed.
2644void Sema::ActOnStartCXXInClassMemberInitializer() {
2645 // Create a synthetic function scope to represent the call to the constructor
2646 // that notionally surrounds a use of this initializer.
2647 PushFunctionScope();
2648}
2649
2650/// \brief This is invoked after parsing an in-class initializer for a
2651/// non-static C++ class member, and after instantiating an in-class initializer
2652/// in a class template. Such actions are deferred until the class is complete.
2653void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2654 SourceLocation InitLoc,
2655 Expr *InitExpr) {
2656 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002657 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002658
David Majnemer87ff66c2014-12-13 11:34:16 +00002659 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2660 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002661 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002662
2663 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002664 D->setInvalidDecl();
2665 if (FD)
2666 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002667 return;
2668 }
2669
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002670 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2671 FD->setInvalidDecl();
2672 FD->removeInClassInitializer();
2673 return;
2674 }
2675
Richard Smith938f40b2011-06-11 17:19:42 +00002676 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002677 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002678 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002679 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002680 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002681 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002682 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2683 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002684 if (Init.isInvalid()) {
2685 FD->setInvalidDecl();
2686 return;
2687 }
Richard Smith938f40b2011-06-11 17:19:42 +00002688 }
2689
Richard Smith945f8d32013-01-14 22:39:08 +00002690 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002691 // The initialization of each base and member constitutes a
2692 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002693 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002694 if (Init.isInvalid()) {
2695 FD->setInvalidDecl();
2696 return;
2697 }
2698
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002699 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002700
2701 FD->setInClassInitializer(InitExpr);
2702}
2703
Douglas Gregor15e77a22009-12-31 09:10:24 +00002704/// \brief Find the direct and/or virtual base specifiers that
2705/// correspond to the given base type, for use in base initialization
2706/// within a constructor.
2707static bool FindBaseInitializer(Sema &SemaRef,
2708 CXXRecordDecl *ClassDecl,
2709 QualType BaseType,
2710 const CXXBaseSpecifier *&DirectBaseSpec,
2711 const CXXBaseSpecifier *&VirtualBaseSpec) {
2712 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002713 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002714 for (const auto &Base : ClassDecl->bases()) {
2715 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002716 // We found a direct base of this type. That's what we're
2717 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002718 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002719 break;
2720 }
2721 }
2722
2723 // Check for a virtual base class.
2724 // FIXME: We might be able to short-circuit this if we know in advance that
2725 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002727 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2728 // We haven't found a base yet; search the class hierarchy for a
2729 // virtual base class.
2730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2731 /*DetectVirtual=*/false);
2732 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2733 BaseType, Paths)) {
2734 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2735 Path != Paths.end(); ++Path) {
2736 if (Path->back().Base->isVirtual()) {
2737 VirtualBaseSpec = Path->back().Base;
2738 break;
2739 }
2740 }
2741 }
2742 }
2743
2744 return DirectBaseSpec || VirtualBaseSpec;
2745}
2746
Sebastian Redla74948d2011-09-24 17:48:25 +00002747/// \brief Handle a C++ member initializer using braced-init-list syntax.
2748MemInitResult
2749Sema::ActOnMemInitializer(Decl *ConstructorD,
2750 Scope *S,
2751 CXXScopeSpec &SS,
2752 IdentifierInfo *MemberOrBase,
2753 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002754 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002755 SourceLocation IdLoc,
2756 Expr *InitList,
2757 SourceLocation EllipsisLoc) {
2758 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002759 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002760 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002761}
2762
2763/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002764MemInitResult
John McCall48871652010-08-21 09:40:31 +00002765Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002766 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002767 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002768 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002769 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002770 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002771 SourceLocation IdLoc,
2772 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002773 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002774 SourceLocation RParenLoc,
2775 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002776 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002777 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002778 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002779 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002780}
2781
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002782namespace {
2783
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002784// Callback to only accept typo corrections that can be a valid C++ member
2785// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002786class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002787public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002788 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2789 : ClassDecl(ClassDecl) {}
2790
Craig Toppera798a9d2014-03-02 09:32:10 +00002791 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002792 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2793 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2794 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002795 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002796 }
2797 return false;
2798 }
2799
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002800private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002801 CXXRecordDecl *ClassDecl;
2802};
2803
2804}
2805
Sebastian Redla74948d2011-09-24 17:48:25 +00002806/// \brief Handle a C++ member initializer.
2807MemInitResult
2808Sema::BuildMemInitializer(Decl *ConstructorD,
2809 Scope *S,
2810 CXXScopeSpec &SS,
2811 IdentifierInfo *MemberOrBase,
2812 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002813 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002814 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002815 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002816 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002817 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2818 if (!Res.isUsable())
2819 return true;
2820 Init = Res.get();
2821
Douglas Gregor71a57182009-06-22 23:20:33 +00002822 if (!ConstructorD)
2823 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002825 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002826
2827 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002828 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002829 if (!Constructor) {
2830 // The user wrote a constructor initializer on a function that is
2831 // not a C++ constructor. Ignore the error for now, because we may
2832 // have more member initializers coming; we'll diagnose it just
2833 // once in ActOnMemInitializers.
2834 return true;
2835 }
2836
2837 CXXRecordDecl *ClassDecl = Constructor->getParent();
2838
2839 // C++ [class.base.init]p2:
2840 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002841 // constructor's class and, if not found in that scope, are looked
2842 // up in the scope containing the constructor's definition.
2843 // [Note: if the constructor's class contains a member with the
2844 // same name as a direct or virtual base class of the class, a
2845 // mem-initializer-id naming the member or base class and composed
2846 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002847 // mem-initializer-id for the hidden base class may be specified
2848 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002849 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002850 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002851 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002852 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002853 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002854 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2855 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002856 if (EllipsisLoc.isValid())
2857 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002858 << MemberOrBase
2859 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002860
Sebastian Redla9351792012-02-11 23:51:47 +00002861 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 }
Francois Pichetd583da02010-12-04 09:14:42 +00002863 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002864 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002865 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002866 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002867 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002868
2869 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002870 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002871 } else if (DS.getTypeSpecType() == TST_decltype) {
2872 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002873 } else {
2874 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2875 LookupParsedName(R, S, &SS);
2876
2877 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2878 if (!TyD) {
2879 if (R.isAmbiguous()) return true;
2880
John McCallda6841b2010-04-09 19:01:14 +00002881 // We don't want access-control diagnostics here.
2882 R.suppressDiagnostics();
2883
Douglas Gregora3b624a2010-01-19 06:46:48 +00002884 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2885 bool NotUnknownSpecialization = false;
2886 DeclContext *DC = computeDeclContext(SS, false);
2887 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2888 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2889
2890 if (!NotUnknownSpecialization) {
2891 // When the scope specifier can refer to a member of an unknown
2892 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002893 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2894 SS.getWithLocInContext(Context),
2895 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002896 if (BaseType.isNull())
2897 return true;
2898
Douglas Gregora3b624a2010-01-19 06:46:48 +00002899 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002900 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002901 }
2902 }
2903
Douglas Gregor15e77a22009-12-31 09:10:24 +00002904 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002905 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002906 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002907 (Corr = CorrectTypo(
2908 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2909 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2910 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002911 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002912 // We have found a non-static data member with a similar
2913 // name to what was typed; complain and initialize that
2914 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002915 diagnoseTypo(Corr,
2916 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2917 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002918 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002919 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002920 const CXXBaseSpecifier *DirectBaseSpec;
2921 const CXXBaseSpecifier *VirtualBaseSpec;
2922 if (FindBaseInitializer(*this, ClassDecl,
2923 Context.getTypeDeclType(Type),
2924 DirectBaseSpec, VirtualBaseSpec)) {
2925 // We have found a direct or virtual base class with a
2926 // similar name to what was typed; complain and initialize
2927 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002928 diagnoseTypo(Corr,
2929 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2930 << MemberOrBase << false,
2931 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002932
Richard Smithf9b15102013-08-17 00:46:16 +00002933 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2934 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002935 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002936 diag::note_base_class_specified_here)
2937 << BaseSpec->getType()
2938 << BaseSpec->getSourceRange();
2939
Douglas Gregor15e77a22009-12-31 09:10:24 +00002940 TyD = Type;
2941 }
2942 }
2943 }
2944
Douglas Gregora3b624a2010-01-19 06:46:48 +00002945 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002946 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002947 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002948 return true;
2949 }
John McCallb5a0d312009-12-21 10:41:20 +00002950 }
2951
Douglas Gregora3b624a2010-01-19 06:46:48 +00002952 if (BaseType.isNull()) {
2953 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002954 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00002955 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002956 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002957 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2958 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002959 }
2960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961
John McCallbcd03502009-12-07 02:54:59 +00002962 if (!TInfo)
2963 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002964
Sebastian Redla9351792012-02-11 23:51:47 +00002965 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002966}
2967
Chandler Carruth599deef2011-09-03 01:14:15 +00002968/// Checks a member initializer expression for cases where reference (or
2969/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002970static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2971 Expr *Init,
2972 SourceLocation IdLoc) {
2973 QualType MemberTy = Member->getType();
2974
2975 // We only handle pointers and references currently.
2976 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2977 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2978 return;
2979
2980 const bool IsPointer = MemberTy->isPointerType();
2981 if (IsPointer) {
2982 if (const UnaryOperator *Op
2983 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2984 // The only case we're worried about with pointers requires taking the
2985 // address.
2986 if (Op->getOpcode() != UO_AddrOf)
2987 return;
2988
2989 Init = Op->getSubExpr();
2990 } else {
2991 // We only handle address-of expression initializers for pointers.
2992 return;
2993 }
2994 }
2995
Richard Smithe3b28bc2013-06-12 21:51:50 +00002996 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002997 // We only warn when referring to a non-reference parameter declaration.
2998 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2999 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003000 return;
3001
3002 S.Diag(Init->getExprLoc(),
3003 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3004 : diag::warn_bind_ref_member_to_parameter)
3005 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003006 } else {
3007 // Other initializers are fine.
3008 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003009 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003010
3011 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3012 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003013}
3014
John McCallfaf5fb42010-08-26 23:41:50 +00003015MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003016Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003017 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003018 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3019 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3020 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003021 "Member must be a FieldDecl or IndirectFieldDecl");
3022
Sebastian Redla9351792012-02-11 23:51:47 +00003023 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003024 return true;
3025
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003026 if (Member->isInvalidDecl())
3027 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003028
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003029 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003030 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003031 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003032 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003033 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003034 } else {
3035 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003036 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003037 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003038
Sebastian Redla9351792012-02-11 23:51:47 +00003039 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003040
Sebastian Redla9351792012-02-11 23:51:47 +00003041 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003042 // Can't check initialization for a member of dependent type or when
3043 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003044 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003045 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003046 bool InitList = false;
3047 if (isa<InitListExpr>(Init)) {
3048 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003049 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003050 }
3051
Chandler Carruthd44c3102010-12-06 09:23:57 +00003052 // Initialize the member.
3053 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003054 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3055 : InitializedEntity::InitializeMember(IndirectMember,
3056 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003057 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003058 InitList ? InitializationKind::CreateDirectList(IdLoc)
3059 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3060 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003061
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003062 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003063 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3064 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003065 if (MemberInit.isInvalid())
3066 return true;
3067
Richard Smith736a9472013-06-12 20:42:33 +00003068 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3069
Richard Smith945f8d32013-01-14 22:39:08 +00003070 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003071 // The initialization of each base and member constitutes a
3072 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003073 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003074 if (MemberInit.isInvalid())
3075 return true;
3076
Richard Smithd59b8322012-12-19 01:39:02 +00003077 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003078 }
3079
Chandler Carruthd44c3102010-12-06 09:23:57 +00003080 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003081 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3082 InitRange.getBegin(), Init,
3083 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003084 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003085 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3086 InitRange.getBegin(), Init,
3087 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003088 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003089}
3090
John McCallfaf5fb42010-08-26 23:41:50 +00003091MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003092Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003093 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003094 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003095 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003096 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003097 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003098 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003099
Sebastian Redl0501c632012-02-12 16:37:36 +00003100 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003101 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003102 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3103 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003104 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003105 }
3106
Sebastian Redla9351792012-02-11 23:51:47 +00003107 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003108 // Initialize the object.
3109 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3110 QualType(ClassDecl->getTypeForDecl(), 0));
3111 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003112 InitList ? InitializationKind::CreateDirectList(NameLoc)
3113 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3114 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003115 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003116 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003117 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003118 if (DelegationInit.isInvalid())
3119 return true;
3120
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003121 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3122 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003123
Richard Smith945f8d32013-01-14 22:39:08 +00003124 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003125 // The initialization of each base and member constitutes a
3126 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003127 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3128 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003129 if (DelegationInit.isInvalid())
3130 return true;
3131
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003132 // If we are in a dependent context, template instantiation will
3133 // perform this type-checking again. Just save the arguments that we
3134 // received in a ParenListExpr.
3135 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3136 // of the information that we have about the base
3137 // initializer. However, deconstructing the ASTs is a dicey process,
3138 // and this approach is far more likely to get the corner cases right.
3139 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003140 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003141
Sebastian Redla9351792012-02-11 23:51:47 +00003142 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003143 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003144 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003145}
3146
3147MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003148Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003149 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003150 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003151 SourceLocation BaseLoc
3152 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003153
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003154 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3155 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3156 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3157
3158 // C++ [class.base.init]p2:
3159 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003160 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003161 // of that class, the mem-initializer is ill-formed. A
3162 // mem-initializer-list can initialize a base class using any
3163 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003164 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003165
Sebastian Redla9351792012-02-11 23:51:47 +00003166 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003167 if (EllipsisLoc.isValid()) {
3168 // This is a pack expansion.
3169 if (!BaseType->containsUnexpandedParameterPack()) {
3170 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003171 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003172
Douglas Gregor44e7df62011-01-04 00:32:56 +00003173 EllipsisLoc = SourceLocation();
3174 }
3175 } else {
3176 // Check for any unexpanded parameter packs.
3177 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3178 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003179
Sebastian Redla9351792012-02-11 23:51:47 +00003180 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003181 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003182 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003183
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003184 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003185 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3186 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003187 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003188 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3189 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003190 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003191
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003192 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3193 VirtualBaseSpec);
3194
3195 // C++ [base.class.init]p2:
3196 // Unless the mem-initializer-id names a nonstatic data member of the
3197 // constructor's class or a direct or virtual base of that class, the
3198 // mem-initializer is ill-formed.
3199 if (!DirectBaseSpec && !VirtualBaseSpec) {
3200 // If the class has any dependent bases, then it's possible that
3201 // one of those types will resolve to the same type as
3202 // BaseType. Therefore, just treat this as a dependent base
3203 // class initialization. FIXME: Should we try to check the
3204 // initialization anyway? It seems odd.
3205 if (ClassDecl->hasAnyDependentBases())
3206 Dependent = true;
3207 else
3208 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3209 << BaseType << Context.getTypeDeclType(ClassDecl)
3210 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3211 }
3212 }
3213
3214 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003215 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003216
Sebastian Redla74948d2011-09-24 17:48:25 +00003217 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3218 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003219 InitRange.getBegin(), Init,
3220 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003221 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003222
3223 // C++ [base.class.init]p2:
3224 // If a mem-initializer-id is ambiguous because it designates both
3225 // a direct non-virtual base class and an inherited virtual base
3226 // class, the mem-initializer is ill-formed.
3227 if (DirectBaseSpec && VirtualBaseSpec)
3228 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003229 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003230
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003231 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003232 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003233 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003234
3235 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003236 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003237 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003238 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003239 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003240 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003241 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003242
3243 InitializedEntity BaseEntity =
3244 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3245 InitializationKind Kind =
3246 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3247 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3248 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003249 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003250 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003251 if (BaseInit.isInvalid())
3252 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003253
Richard Smith945f8d32013-01-14 22:39:08 +00003254 // C++11 [class.base.init]p7:
3255 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003256 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003257 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003258 if (BaseInit.isInvalid())
3259 return true;
3260
3261 // If we are in a dependent context, template instantiation will
3262 // perform this type-checking again. Just save the arguments that we
3263 // received in a ParenListExpr.
3264 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3265 // of the information that we have about the base
3266 // initializer. However, deconstructing the ASTs is a dicey process,
3267 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003268 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003269 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003270
Alexis Hunt1d792652011-01-08 20:30:50 +00003271 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003272 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003273 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003274 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003275 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003276}
3277
Sebastian Redl22653ba2011-08-30 19:58:05 +00003278// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003279static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3280 if (T.isNull()) T = E->getType();
3281 QualType TargetType = SemaRef.BuildReferenceType(
3282 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003283 SourceLocation ExprLoc = E->getLocStart();
3284 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3285 TargetType, ExprLoc);
3286
3287 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3288 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003289 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003290}
3291
Anders Carlsson1b00e242010-04-23 03:10:23 +00003292/// ImplicitInitializerKind - How an implicit base or member initializer should
3293/// initialize its base or member.
3294enum ImplicitInitializerKind {
3295 IIK_Default,
3296 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003297 IIK_Move,
3298 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003299};
3300
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003301static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003302BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003303 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003304 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003305 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003306 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003307 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003308 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3309 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003310
John McCalldadc5752010-08-24 06:29:42 +00003311 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003312
3313 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003314 case IIK_Inherit: {
3315 const CXXRecordDecl *Inherited =
3316 Constructor->getInheritedConstructor()->getParent();
3317 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3318 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3319 // C++11 [class.inhctor]p8:
3320 // Each expression in the expression-list is of the form
3321 // static_cast<T&&>(p), where p is the name of the corresponding
3322 // constructor parameter and T is the declared type of p.
3323 SmallVector<Expr*, 16> Args;
3324 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3325 ParmVarDecl *PD = Constructor->getParamDecl(I);
3326 ExprResult ArgExpr =
3327 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3328 VK_LValue, SourceLocation());
3329 if (ArgExpr.isInvalid())
3330 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003331 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003332 }
3333
3334 InitializationKind InitKind = InitializationKind::CreateDirect(
3335 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003336 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003337 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3338 break;
3339 }
3340 }
3341 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003342 case IIK_Default: {
3343 InitializationKind InitKind
3344 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003345 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3346 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003347 break;
3348 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003349
Sebastian Redl22653ba2011-08-30 19:58:05 +00003350 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003351 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003352 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003353 ParmVarDecl *Param = Constructor->getParamDecl(0);
3354 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003355
Anders Carlsson1b00e242010-04-23 03:10:23 +00003356 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003357 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003358 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003359 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003360 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003361
Eli Friedmanfa0df832012-02-02 03:46:19 +00003362 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3363
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003364 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003365 QualType ArgTy =
3366 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3367 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003368
Sebastian Redl22653ba2011-08-30 19:58:05 +00003369 if (Moving) {
3370 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3371 }
3372
John McCallcf142162010-08-07 06:22:56 +00003373 CXXCastPath BasePath;
3374 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003375 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3376 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003377 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003378 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003379
Anders Carlsson1b00e242010-04-23 03:10:23 +00003380 InitializationKind InitKind
3381 = InitializationKind::CreateDirect(Constructor->getLocation(),
3382 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003383 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3384 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003385 break;
3386 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003387 }
John McCallb268a282010-08-23 23:25:46 +00003388
Douglas Gregora40433a2010-12-07 00:41:46 +00003389 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003390 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003391 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003392
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003393 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003394 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003395 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3396 SourceLocation()),
3397 BaseSpec->isVirtual(),
3398 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003399 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003400 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003401 SourceLocation());
3402
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003403 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003404}
3405
Sebastian Redl22653ba2011-08-30 19:58:05 +00003406static bool RefersToRValueRef(Expr *MemRef) {
3407 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3408 return Referenced->getType()->isRValueReferenceType();
3409}
3410
Anders Carlsson3c1db572010-04-23 02:15:47 +00003411static bool
3412BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003413 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003414 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003415 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003416 if (Field->isInvalidDecl())
3417 return true;
3418
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003419 SourceLocation Loc = Constructor->getLocation();
3420
Sebastian Redl22653ba2011-08-30 19:58:05 +00003421 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3422 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003423 ParmVarDecl *Param = Constructor->getParamDecl(0);
3424 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003425
3426 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003427 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3428 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003429
Anders Carlsson423f5d82010-04-23 16:04:08 +00003430 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003431 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003432 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003434
Eli Friedmanfa0df832012-02-02 03:46:19 +00003435 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3436
Sebastian Redl22653ba2011-08-30 19:58:05 +00003437 if (Moving) {
3438 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3439 }
3440
Douglas Gregor94f9a482010-05-05 05:51:00 +00003441 // Build a reference to this field within the parameter.
3442 CXXScopeSpec SS;
3443 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3444 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003445 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3446 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003447 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003448 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003449 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003450 ParamType, Loc,
3451 /*IsArrow=*/false,
3452 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003453 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003454 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003455 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003456 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003457 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003458 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003459
3460 // C++11 [class.copy]p15:
3461 // - if a member m has rvalue reference type T&&, it is direct-initialized
3462 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003463 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003464 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003465 }
3466
Douglas Gregor94f9a482010-05-05 05:51:00 +00003467 // When the field we are copying is an array, create index variables for
3468 // each dimension of the array. We use these index variables to subscript
3469 // the source array, and other clients (e.g., CodeGen) will perform the
3470 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003471 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003472 QualType BaseType = Field->getType();
3473 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003474 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003475 while (const ConstantArrayType *Array
3476 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003477 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003478 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003479 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003480 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003481 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003482 llvm::raw_svector_ostream OS(Str);
3483 OS << "__i" << IndexVariables.size();
3484 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3485 }
3486 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003487 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003488 IterationVarName, SizeType,
3489 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003490 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003491 IndexVariables.push_back(IterationVar);
3492
3493 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003494 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003495 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003496 assert(!IterationVarRef.isInvalid() &&
3497 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003498 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003499 assert(!IterationVarRef.isInvalid() &&
3500 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003501
Douglas Gregor94f9a482010-05-05 05:51:00 +00003502 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003503 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3504 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003505 Loc);
3506 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003507 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003508
Douglas Gregor94f9a482010-05-05 05:51:00 +00003509 BaseType = Array->getElementType();
3510 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003511
3512 // The array subscript expression is an lvalue, which is wrong for moving.
3513 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003514 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003515
Douglas Gregor94f9a482010-05-05 05:51:00 +00003516 // Construct the entity that we will be initializing. For an array, this
3517 // will be first element in the array, which may require several levels
3518 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003519 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003520 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003521 if (Indirect)
3522 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3523 else
3524 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003525 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3526 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3527 0,
3528 Entities.back()));
3529
3530 // Direct-initialize to use the copy constructor.
3531 InitializationKind InitKind =
3532 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3533
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003534 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003535 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003536
John McCalldadc5752010-08-24 06:29:42 +00003537 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003538 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003539 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003540 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003541 if (MemberInit.isInvalid())
3542 return true;
3543
Douglas Gregor493627b2011-08-10 15:22:55 +00003544 if (Indirect) {
3545 assert(IndexVariables.size() == 0 &&
3546 "Indirect field improperly initialized");
3547 CXXMemberInit
3548 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3549 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003550 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003551 Loc);
3552 } else
3553 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003554 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003555 Loc,
3556 IndexVariables.data(),
3557 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003558 return false;
3559 }
3560
Richard Smithc2bc61b2013-03-18 21:12:30 +00003561 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3562 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003563
Anders Carlsson3c1db572010-04-23 02:15:47 +00003564 QualType FieldBaseElementType =
3565 SemaRef.Context.getBaseElementType(Field->getType());
3566
Anders Carlsson3c1db572010-04-23 02:15:47 +00003567 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003568 InitializedEntity InitEntity
3569 = Indirect? InitializedEntity::InitializeMember(Indirect)
3570 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003571 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003572 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003573
3574 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3575 ExprResult MemberInit =
3576 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003577
Douglas Gregora40433a2010-12-07 00:41:46 +00003578 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003579 if (MemberInit.isInvalid())
3580 return true;
3581
Douglas Gregor493627b2011-08-10 15:22:55 +00003582 if (Indirect)
3583 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3584 Indirect, Loc,
3585 Loc,
3586 MemberInit.get(),
3587 Loc);
3588 else
3589 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3590 Field, Loc, Loc,
3591 MemberInit.get(),
3592 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003593 return false;
3594 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003595
Alexis Hunt8b455182011-05-17 00:19:05 +00003596 if (!Field->getParent()->isUnion()) {
3597 if (FieldBaseElementType->isReferenceType()) {
3598 SemaRef.Diag(Constructor->getLocation(),
3599 diag::err_uninitialized_member_in_ctor)
3600 << (int)Constructor->isImplicit()
3601 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3602 << 0 << Field->getDeclName();
3603 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3604 return true;
3605 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003606
Alexis Hunt8b455182011-05-17 00:19:05 +00003607 if (FieldBaseElementType.isConstQualified()) {
3608 SemaRef.Diag(Constructor->getLocation(),
3609 diag::err_uninitialized_member_in_ctor)
3610 << (int)Constructor->isImplicit()
3611 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3612 << 1 << Field->getDeclName();
3613 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3614 return true;
3615 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003616 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003617
David Blaikiebbafb8a2012-03-11 07:00:24 +00003618 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003619 FieldBaseElementType->isObjCRetainableType() &&
3620 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3621 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003622 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003623 // Default-initialize Objective-C pointers to NULL.
3624 CXXMemberInit
3625 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3626 Loc, Loc,
3627 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3628 Loc);
3629 return false;
3630 }
3631
Anders Carlsson3c1db572010-04-23 02:15:47 +00003632 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003633 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003634 return false;
3635}
John McCallbc83b3f2010-05-20 23:23:51 +00003636
3637namespace {
3638struct BaseAndFieldInfo {
3639 Sema &S;
3640 CXXConstructorDecl *Ctor;
3641 bool AnyErrorsInInits;
3642 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003643 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003644 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003645 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003646
3647 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3648 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003649 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3650 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003651 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003652 else if (Generated && Ctor->isMoveConstructor())
3653 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003654 else if (Ctor->getInheritedConstructor())
3655 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003656 else
3657 IIK = IIK_Default;
3658 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003659
3660 bool isImplicitCopyOrMove() const {
3661 switch (IIK) {
3662 case IIK_Copy:
3663 case IIK_Move:
3664 return true;
3665
3666 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003667 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003668 return false;
3669 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003670
3671 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003672 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003673
3674 bool addFieldInitializer(CXXCtorInitializer *Init) {
3675 AllToInit.push_back(Init);
3676
3677 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003678 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003679 S.UnusedPrivateFields.remove(Init->getAnyMember());
3680
3681 return false;
3682 }
John McCallbc83b3f2010-05-20 23:23:51 +00003683
Richard Smithab44d5b2013-12-10 08:25:00 +00003684 bool isInactiveUnionMember(FieldDecl *Field) {
3685 RecordDecl *Record = Field->getParent();
3686 if (!Record->isUnion())
3687 return false;
3688
Richard Smith8d183852013-12-10 20:56:03 +00003689 if (FieldDecl *Active =
3690 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003691 return Active != Field->getCanonicalDecl();
3692
3693 // In an implicit copy or move constructor, ignore any in-class initializer.
3694 if (isImplicitCopyOrMove())
3695 return true;
3696
3697 // If there's no explicit initialization, the field is active only if it
3698 // has an in-class initializer...
3699 if (Field->hasInClassInitializer())
3700 return false;
3701 // ... or it's an anonymous struct or union whose class has an in-class
3702 // initializer.
3703 if (!Field->isAnonymousStructOrUnion())
3704 return true;
3705 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3706 return !FieldRD->hasInClassInitializer();
3707 }
3708
3709 /// \brief Determine whether the given field is, or is within, a union member
3710 /// that is inactive (because there was an initializer given for a different
3711 /// member of the union, or because the union was not initialized at all).
3712 bool isWithinInactiveUnionMember(FieldDecl *Field,
3713 IndirectFieldDecl *Indirect) {
3714 if (!Indirect)
3715 return isInactiveUnionMember(Field);
3716
Aaron Ballman29c94602014-03-07 18:36:15 +00003717 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003718 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003719 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003720 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003721 }
3722 return false;
3723 }
3724};
Richard Smithc94ec842011-09-19 13:34:43 +00003725}
3726
Douglas Gregor10f939c2011-11-02 23:04:16 +00003727/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3728/// array type.
3729static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3730 if (T->isIncompleteArrayType())
3731 return true;
3732
3733 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3734 if (!ArrayT->getSize())
3735 return true;
3736
3737 T = ArrayT->getElementType();
3738 }
3739
3740 return false;
3741}
3742
Richard Smith938f40b2011-06-11 17:19:42 +00003743static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003744 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003745 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003746 if (Field->isInvalidDecl())
3747 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003748
Chandler Carruth139e9622010-06-30 02:59:29 +00003749 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003750 if (CXXCtorInitializer *Init =
3751 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003752 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003753
Richard Smithab44d5b2013-12-10 08:25:00 +00003754 // C++11 [class.base.init]p8:
3755 // if the entity is a non-static data member that has a
3756 // brace-or-equal-initializer and either
3757 // -- the constructor's class is a union and no other variant member of that
3758 // union is designated by a mem-initializer-id or
3759 // -- the constructor's class is not a union, and, if the entity is a member
3760 // of an anonymous union, no other member of that union is designated by
3761 // a mem-initializer-id,
3762 // the entity is initialized as specified in [dcl.init].
3763 //
3764 // We also apply the same rules to handle anonymous structs within anonymous
3765 // unions.
3766 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3767 return false;
3768
Douglas Gregor7db3e952011-11-28 20:03:15 +00003769 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003770 ExprResult DIE =
3771 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3772 if (DIE.isInvalid())
3773 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003774 CXXCtorInitializer *Init;
3775 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003776 Init = new (SemaRef.Context)
3777 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3778 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003779 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003780 Init = new (SemaRef.Context)
3781 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3782 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003783 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003784 }
3785
Douglas Gregor10f939c2011-11-02 23:04:16 +00003786 // Don't initialize incomplete or zero-length arrays.
3787 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3788 return false;
3789
John McCallbc83b3f2010-05-20 23:23:51 +00003790 // Don't try to build an implicit initializer if there were semantic
3791 // errors in any of the initializers (and therefore we might be
3792 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003793 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003794 return false;
3795
Craig Topperc3ec1492014-05-26 06:22:03 +00003796 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003797 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3798 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003799 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003800
Richard Smith0a8cfc72012-08-07 21:30:42 +00003801 if (!Init)
3802 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003803
Richard Smith0a8cfc72012-08-07 21:30:42 +00003804 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003805}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003806
3807bool
3808Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3809 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003810 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003811 Constructor->setNumCtorInitializers(1);
3812 CXXCtorInitializer **initializer =
3813 new (Context) CXXCtorInitializer*[1];
3814 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3815 Constructor->setCtorInitializers(initializer);
3816
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003817 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003818 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003819 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3820 }
3821
Alexis Hunte2622992011-05-05 00:05:47 +00003822 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003823
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003824 DiagnoseUninitializedFields(*this, Constructor);
3825
Alexis Hunt61bc1732011-05-01 07:04:31 +00003826 return false;
3827}
Douglas Gregor493627b2011-08-10 15:22:55 +00003828
David Blaikie3fc2f912013-01-17 05:26:25 +00003829bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3830 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003831 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003832 // Just store the initializers as written, they will be checked during
3833 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003834 if (!Initializers.empty()) {
3835 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003836 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003837 new (Context) CXXCtorInitializer*[Initializers.size()];
3838 memcpy(baseOrMemberInitializers, Initializers.data(),
3839 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003840 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003841 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003842
3843 // Let template instantiation know whether we had errors.
3844 if (AnyErrors)
3845 Constructor->setInvalidDecl();
3846
Anders Carlssondb0a9652010-04-02 06:26:44 +00003847 return false;
3848 }
3849
John McCallbc83b3f2010-05-20 23:23:51 +00003850 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003851
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003852 // We need to build the initializer AST according to order of construction
3853 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003854 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003855 if (!ClassDecl)
3856 return true;
3857
Eli Friedman9cf6b592009-11-09 19:20:36 +00003858 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003859
David Blaikie3fc2f912013-01-17 05:26:25 +00003860 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003861 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003862
Anders Carlssondb0a9652010-04-02 06:26:44 +00003863 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003864 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003865 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003866 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003867
3868 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003869 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003870 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003871 if (FD && FD->getParent()->isUnion())
3872 Info.ActiveUnionMember.insert(std::make_pair(
3873 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3874 }
3875 } else if (FieldDecl *FD = Member->getMember()) {
3876 if (FD->getParent()->isUnion())
3877 Info.ActiveUnionMember.insert(std::make_pair(
3878 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3879 }
3880 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003881 }
3882
Anders Carlsson43c64af2010-04-21 19:52:01 +00003883 // Keep track of the direct virtual bases.
3884 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003885 for (auto &I : ClassDecl->bases()) {
3886 if (I.isVirtual())
3887 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003888 }
3889
Anders Carlssondb0a9652010-04-02 06:26:44 +00003890 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003891 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003892 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003893 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003894 // [class.base.init]p7, per DR257:
3895 // A mem-initializer where the mem-initializer-id names a virtual base
3896 // class is ignored during execution of a constructor of any class that
3897 // is not the most derived class.
3898 if (ClassDecl->isAbstract()) {
3899 // FIXME: Provide a fixit to remove the base specifier. This requires
3900 // tracking the location of the associated comma for a base specifier.
3901 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003902 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003903 DiagnoseAbstractType(ClassDecl);
3904 }
3905
John McCallbc83b3f2010-05-20 23:23:51 +00003906 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003907 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3908 // [class.base.init]p8, per DR257:
3909 // If a given [...] base class is not named by a mem-initializer-id
3910 // [...] and the entity is not a virtual base class of an abstract
3911 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003912 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003913 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003914 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003915 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003916 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003917 HadError = true;
3918 continue;
3919 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003920
John McCallbc83b3f2010-05-20 23:23:51 +00003921 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003922 }
3923 }
Mike Stump11289f42009-09-09 15:08:12 +00003924
John McCallbc83b3f2010-05-20 23:23:51 +00003925 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003926 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003927 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003928 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003929 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003930
Alexis Hunt1d792652011-01-08 20:30:50 +00003931 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003932 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003933 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003934 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003935 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003936 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003937 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003938 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003939 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003940 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003941 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003942
John McCallbc83b3f2010-05-20 23:23:51 +00003943 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003944 }
3945 }
Mike Stump11289f42009-09-09 15:08:12 +00003946
John McCallbc83b3f2010-05-20 23:23:51 +00003947 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003948 for (auto *Mem : ClassDecl->decls()) {
3949 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003950 // C++ [class.bit]p2:
3951 // A declaration for a bit-field that omits the identifier declares an
3952 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3953 // initialized.
3954 if (F->isUnnamedBitfield())
3955 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003956
Sebastian Redl22653ba2011-08-30 19:58:05 +00003957 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003958 // handle anonymous struct/union fields based on their individual
3959 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003960 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003961 continue;
3962
3963 if (CollectFieldInitializer(*this, Info, F))
3964 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003965 continue;
3966 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003967
3968 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003969 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003970 continue;
3971
Aaron Ballman629afae2014-03-07 19:56:05 +00003972 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003973 if (F->getType()->isIncompleteArrayType()) {
3974 assert(ClassDecl->hasFlexibleArrayMember() &&
3975 "Incomplete array type is not valid");
3976 continue;
3977 }
3978
Douglas Gregor493627b2011-08-10 15:22:55 +00003979 // Initialize each field of an anonymous struct individually.
3980 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3981 HadError = true;
3982
3983 continue;
3984 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
David Blaikie3fc2f912013-01-17 05:26:25 +00003987 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003988 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003989 Constructor->setNumCtorInitializers(NumInitializers);
3990 CXXCtorInitializer **baseOrMemberInitializers =
3991 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003992 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003993 NumInitializers * sizeof(CXXCtorInitializer*));
3994 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003995
John McCalla6309952010-03-16 21:39:52 +00003996 // Constructors implicitly reference the base and member
3997 // destructors.
3998 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3999 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004000 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004001
4002 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004003}
4004
David Blaikieb61b8152013-01-17 08:49:22 +00004005static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004006 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004007 const RecordDecl *RD = RT->getDecl();
4008 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004009 for (auto *Field : RD->fields())
4010 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004011 return;
4012 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004013 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004014 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004015}
4016
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004017static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4018 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004019}
4020
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004021static const void *GetKeyForMember(ASTContext &Context,
4022 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004023 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004024 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004025
Richard Smithcd45dbc2014-04-19 03:48:30 +00004026 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004027}
4028
David Blaikie3fc2f912013-01-17 05:26:25 +00004029static void DiagnoseBaseOrMemInitializerOrder(
4030 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4031 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004032 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004033 return;
Mike Stump11289f42009-09-09 15:08:12 +00004034
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004035 // Don't check initializers order unless the warning is enabled at the
4036 // location of at least one initializer.
4037 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004038 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004039 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004040 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4041 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004042 ShouldCheckOrder = true;
4043 break;
4044 }
4045 }
4046 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004047 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004048
John McCallbb7b6582010-04-10 07:37:23 +00004049 // Build the list of bases and members in the order that they'll
4050 // actually be initialized. The explicit initializers should be in
4051 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004052 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004053
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004054 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4055
John McCallbb7b6582010-04-10 07:37:23 +00004056 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004057 for (const auto &VBase : ClassDecl->vbases())
4058 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCallbb7b6582010-04-10 07:37:23 +00004060 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004061 for (const auto &Base : ClassDecl->bases()) {
4062 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004063 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004064 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004065 }
Mike Stump11289f42009-09-09 15:08:12 +00004066
John McCallbb7b6582010-04-10 07:37:23 +00004067 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004068 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004069 if (Field->isUnnamedBitfield())
4070 continue;
4071
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004072 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004073 }
4074
John McCallbb7b6582010-04-10 07:37:23 +00004075 unsigned NumIdealInits = IdealInitKeys.size();
4076 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004077
Craig Topperc3ec1492014-05-26 06:22:03 +00004078 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004079 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004080 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004081 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004082
4083 // Scan forward to try to find this initializer in the idealized
4084 // initializers list.
4085 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4086 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004087 break;
John McCallbb7b6582010-04-10 07:37:23 +00004088
4089 // If we didn't find this initializer, it must be because we
4090 // scanned past it on a previous iteration. That can only
4091 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004092 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004093 Sema::SemaDiagnosticBuilder D =
4094 SemaRef.Diag(PrevInit->getSourceLocation(),
4095 diag::warn_initializer_out_of_order);
4096
Francois Pichetd583da02010-12-04 09:14:42 +00004097 if (PrevInit->isAnyMemberInitializer())
4098 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004099 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004100 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004101
Francois Pichetd583da02010-12-04 09:14:42 +00004102 if (Init->isAnyMemberInitializer())
4103 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004104 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004105 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004106
4107 // Move back to the initializer's location in the ideal list.
4108 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4109 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004110 break;
John McCallbb7b6582010-04-10 07:37:23 +00004111
4112 assert(IdealIndex != NumIdealInits &&
4113 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004114 }
John McCallbb7b6582010-04-10 07:37:23 +00004115
4116 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004117 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004118}
4119
John McCall23eebd92010-04-10 09:28:51 +00004120namespace {
4121bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004122 CXXCtorInitializer *Init,
4123 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004124 if (!PrevInit) {
4125 PrevInit = Init;
4126 return false;
4127 }
4128
Douglas Gregorea306a12013-03-25 23:28:23 +00004129 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004130 S.Diag(Init->getSourceLocation(),
4131 diag::err_multiple_mem_initialization)
4132 << Field->getDeclName()
4133 << Init->getSourceRange();
4134 else {
John McCall424cec92011-01-19 06:33:43 +00004135 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004136 assert(BaseClass && "neither field nor base");
4137 S.Diag(Init->getSourceLocation(),
4138 diag::err_multiple_base_initialization)
4139 << QualType(BaseClass, 0)
4140 << Init->getSourceRange();
4141 }
4142 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4143 << 0 << PrevInit->getSourceRange();
4144
4145 return true;
4146}
4147
Alexis Hunt1d792652011-01-08 20:30:50 +00004148typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004149typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4150
4151bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004152 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004153 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004154 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004155 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004156 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004157
4158 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004159 if (Parent->isUnion()) {
4160 UnionEntry &En = Unions[Parent];
4161 if (En.first && En.first != Child) {
4162 S.Diag(Init->getSourceLocation(),
4163 diag::err_multiple_mem_union_initialization)
4164 << Field->getDeclName()
4165 << Init->getSourceRange();
4166 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4167 << 0 << En.second->getSourceRange();
4168 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004169 }
4170 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004171 En.first = Child;
4172 En.second = Init;
4173 }
David Blaikie0f65d592011-11-17 06:01:57 +00004174 if (!Parent->isAnonymousStructOrUnion())
4175 return false;
John McCall23eebd92010-04-10 09:28:51 +00004176 }
4177
4178 Child = Parent;
4179 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004180 }
John McCall23eebd92010-04-10 09:28:51 +00004181
4182 return false;
4183}
4184}
4185
Anders Carlssone857b292010-04-02 03:37:03 +00004186/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004187void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004188 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004189 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004190 bool AnyErrors) {
4191 if (!ConstructorDecl)
4192 return;
4193
4194 AdjustDeclIfTemplate(ConstructorDecl);
4195
4196 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004197 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004198
4199 if (!Constructor) {
4200 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4201 return;
4202 }
4203
John McCall23eebd92010-04-10 09:28:51 +00004204 // Mapping for the duplicate initializers check.
4205 // For member initializers, this is keyed with a FieldDecl*.
4206 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004207 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004208
4209 // Mapping for the inconsistent anonymous-union initializers check.
4210 RedundantUnionMap MemberUnions;
4211
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004212 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004213 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004214 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004215
Abramo Bagnara341d7832010-05-26 18:09:23 +00004216 // Set the source order index.
4217 Init->setSourceOrder(i);
4218
Francois Pichetd583da02010-12-04 09:14:42 +00004219 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004220 const void *Key = GetKeyForMember(Context, Init);
4221 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004222 CheckRedundantUnionInit(*this, Init, MemberUnions))
4223 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004224 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004225 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004226 if (CheckRedundantInit(*this, Init, Members[Key]))
4227 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004228 } else {
4229 assert(Init->isDelegatingInitializer());
4230 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004231 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004232 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004233 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004234 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004235 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004236 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004237 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004238 // Return immediately as the initializer is set.
4239 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004240 }
Anders Carlssone857b292010-04-02 03:37:03 +00004241 }
4242
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004243 if (HadError)
4244 return;
4245
David Blaikie3fc2f912013-01-17 05:26:25 +00004246 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004247
David Blaikie3fc2f912013-01-17 05:26:25 +00004248 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004249
Richard Trieuef64e942013-10-25 00:56:00 +00004250 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004251}
4252
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004253void
John McCalla6309952010-03-16 21:39:52 +00004254Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4255 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004256 // Ignore dependent contexts. Also ignore unions, since their members never
4257 // have destructors implicitly called.
4258 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004259 return;
John McCall1064d7e2010-03-16 05:22:47 +00004260
4261 // FIXME: all the access-control diagnostics are positioned on the
4262 // field/base declaration. That's probably good; that said, the
4263 // user might reasonably want to know why the destructor is being
4264 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004265
Anders Carlssondee9a302009-11-17 04:44:12 +00004266 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004267 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004268 if (Field->isInvalidDecl())
4269 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004270
4271 // Don't destroy incomplete or zero-length arrays.
4272 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4273 continue;
4274
Anders Carlssondee9a302009-11-17 04:44:12 +00004275 QualType FieldType = Context.getBaseElementType(Field->getType());
4276
4277 const RecordType* RT = FieldType->getAs<RecordType>();
4278 if (!RT)
4279 continue;
4280
4281 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004282 if (FieldClassDecl->isInvalidDecl())
4283 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004284 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004285 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004286 // The destructor for an implicit anonymous union member is never invoked.
4287 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4288 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004289
Douglas Gregore71edda2010-07-01 22:47:18 +00004290 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004291 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004292 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004293 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004294 << Field->getDeclName()
4295 << FieldType);
4296
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004297 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004298 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004299 }
4300
John McCall1064d7e2010-03-16 05:22:47 +00004301 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4302
Anders Carlssondee9a302009-11-17 04:44:12 +00004303 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004304 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004305 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004306 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004307
4308 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004309 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004310 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004311
John McCall1064d7e2010-03-16 05:22:47 +00004312 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004313 // If our base class is invalid, we probably can't get its dtor anyway.
4314 if (BaseClassDecl->isInvalidDecl())
4315 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004316 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004317 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004318
Douglas Gregore71edda2010-07-01 22:47:18 +00004319 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004320 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004321
4322 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004323 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004324 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004325 << Base.getType()
4326 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004327 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004328
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004329 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004330 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004331 }
4332
4333 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004334 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004335 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004336 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004337
4338 // Ignore direct virtual bases.
4339 if (DirectVirtualBases.count(RT))
4340 continue;
4341
John McCall1064d7e2010-03-16 05:22:47 +00004342 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004343 // If our base class is invalid, we probably can't get its dtor anyway.
4344 if (BaseClassDecl->isInvalidDecl())
4345 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004346 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004347 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004348
Douglas Gregore71edda2010-07-01 22:47:18 +00004349 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004350 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004351 if (CheckDestructorAccess(
4352 ClassDecl->getLocation(), Dtor,
4353 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004354 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004355 Context.getTypeDeclType(ClassDecl)) ==
4356 AR_accessible) {
4357 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004358 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004359 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004360 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004361 }
John McCall1064d7e2010-03-16 05:22:47 +00004362
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004363 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004364 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004365 }
4366}
4367
John McCall48871652010-08-21 09:40:31 +00004368void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004369 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004370 return;
Mike Stump11289f42009-09-09 15:08:12 +00004371
Mike Stump11289f42009-09-09 15:08:12 +00004372 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004373 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004374 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004375 DiagnoseUninitializedFields(*this, Constructor);
4376 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004377}
4378
Mike Stump11289f42009-09-09 15:08:12 +00004379bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004380 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004381 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4382 unsigned DiagID;
4383 AbstractDiagSelID SelID;
4384
4385 public:
4386 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4387 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004388
Craig Toppera798a9d2014-03-02 09:32:10 +00004389 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004390 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004391 if (SelID == -1)
4392 S.Diag(Loc, DiagID) << T;
4393 else
4394 S.Diag(Loc, DiagID) << SelID << T;
4395 }
4396 } Diagnoser(DiagID, SelID);
4397
4398 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004399}
4400
Anders Carlssoneabf7702009-08-27 00:13:57 +00004401bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004402 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004403 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004404 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004406 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004407 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004408
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004409 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004410 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004411 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004412 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004413
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004414 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004415 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004416 }
Mike Stump11289f42009-09-09 15:08:12 +00004417
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004418 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004419 if (!RT)
4420 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004421
John McCall67da35c2010-02-04 22:26:26 +00004422 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004423
John McCall02db245d2010-08-18 09:41:07 +00004424 // We can't answer whether something is abstract until it has a
4425 // definition. If it's currently being defined, we'll walk back
4426 // over all the declarations when we have a full definition.
4427 const CXXRecordDecl *Def = RD->getDefinition();
4428 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004429 return false;
4430
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004431 if (!RD->isAbstract())
4432 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregorae298422012-05-04 17:09:59 +00004434 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004435 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004436
John McCall02db245d2010-08-18 09:41:07 +00004437 return true;
4438}
4439
4440void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4441 // Check if we've already emitted the list of pure virtual functions
4442 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004443 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004444 return;
Mike Stump11289f42009-09-09 15:08:12 +00004445
Richard Smithbc46e432013-07-22 02:56:56 +00004446 // If the diagnostic is suppressed, don't emit the notes. We're only
4447 // going to emit them once, so try to attach them to a diagnostic we're
4448 // actually going to show.
4449 if (Diags.isLastDiagnosticIgnored())
4450 return;
4451
Douglas Gregor4165bd62010-03-23 23:47:56 +00004452 CXXFinalOverriderMap FinalOverriders;
4453 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004454
Anders Carlssona2f74f32010-06-03 01:00:02 +00004455 // Keep a set of seen pure methods so we won't diagnose the same method
4456 // more than once.
4457 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4458
Douglas Gregor4165bd62010-03-23 23:47:56 +00004459 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4460 MEnd = FinalOverriders.end();
4461 M != MEnd;
4462 ++M) {
4463 for (OverridingMethods::iterator SO = M->second.begin(),
4464 SOEnd = M->second.end();
4465 SO != SOEnd; ++SO) {
4466 // C++ [class.abstract]p4:
4467 // A class is abstract if it contains or inherits at least one
4468 // pure virtual function for which the final overrider is pure
4469 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004470
Douglas Gregor4165bd62010-03-23 23:47:56 +00004471 //
4472 if (SO->second.size() != 1)
4473 continue;
4474
4475 if (!SO->second.front().Method->isPure())
4476 continue;
4477
David Blaikie82e95a32014-11-19 07:49:47 +00004478 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004479 continue;
4480
Douglas Gregor4165bd62010-03-23 23:47:56 +00004481 Diag(SO->second.front().Method->getLocation(),
4482 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004483 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004484 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004485 }
4486
4487 if (!PureVirtualClassDiagSet)
4488 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4489 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004490}
4491
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004492namespace {
John McCall02db245d2010-08-18 09:41:07 +00004493struct AbstractUsageInfo {
4494 Sema &S;
4495 CXXRecordDecl *Record;
4496 CanQualType AbstractType;
4497 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004498
John McCall02db245d2010-08-18 09:41:07 +00004499 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4500 : S(S), Record(Record),
4501 AbstractType(S.Context.getCanonicalType(
4502 S.Context.getTypeDeclType(Record))),
4503 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004504
John McCall02db245d2010-08-18 09:41:07 +00004505 void DiagnoseAbstractType() {
4506 if (Invalid) return;
4507 S.DiagnoseAbstractType(Record);
4508 Invalid = true;
4509 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004510
John McCall02db245d2010-08-18 09:41:07 +00004511 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4512};
4513
4514struct CheckAbstractUsage {
4515 AbstractUsageInfo &Info;
4516 const NamedDecl *Ctx;
4517
4518 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4519 : Info(Info), Ctx(Ctx) {}
4520
4521 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4522 switch (TL.getTypeLocClass()) {
4523#define ABSTRACT_TYPELOC(CLASS, PARENT)
4524#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004525 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004526#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004527 }
John McCall02db245d2010-08-18 09:41:07 +00004528 }
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall02db245d2010-08-18 09:41:07 +00004530 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004531 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004532 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4533 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004534 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004535
4536 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004537 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004538 }
John McCall02db245d2010-08-18 09:41:07 +00004539 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004540
John McCall02db245d2010-08-18 09:41:07 +00004541 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4542 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4543 }
Mike Stump11289f42009-09-09 15:08:12 +00004544
John McCall02db245d2010-08-18 09:41:07 +00004545 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4546 // Visit the type parameters from a permissive context.
4547 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4548 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4549 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4550 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4551 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4552 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004553 }
John McCall02db245d2010-08-18 09:41:07 +00004554 }
Mike Stump11289f42009-09-09 15:08:12 +00004555
John McCall02db245d2010-08-18 09:41:07 +00004556 // Visit pointee types from a permissive context.
4557#define CheckPolymorphic(Type) \
4558 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4559 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4560 }
4561 CheckPolymorphic(PointerTypeLoc)
4562 CheckPolymorphic(ReferenceTypeLoc)
4563 CheckPolymorphic(MemberPointerTypeLoc)
4564 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004565 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004566
John McCall02db245d2010-08-18 09:41:07 +00004567 /// Handle all the types we haven't given a more specific
4568 /// implementation for above.
4569 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4570 // Every other kind of type that we haven't called out already
4571 // that has an inner type is either (1) sugar or (2) contains that
4572 // inner type in some way as a subobject.
4573 if (TypeLoc Next = TL.getNextTypeLoc())
4574 return Visit(Next, Sel);
4575
4576 // If there's no inner type and we're in a permissive context,
4577 // don't diagnose.
4578 if (Sel == Sema::AbstractNone) return;
4579
4580 // Check whether the type matches the abstract type.
4581 QualType T = TL.getType();
4582 if (T->isArrayType()) {
4583 Sel = Sema::AbstractArrayType;
4584 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004585 }
John McCall02db245d2010-08-18 09:41:07 +00004586 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4587 if (CT != Info.AbstractType) return;
4588
4589 // It matched; do some magic.
4590 if (Sel == Sema::AbstractArrayType) {
4591 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4592 << T << TL.getSourceRange();
4593 } else {
4594 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4595 << Sel << T << TL.getSourceRange();
4596 }
4597 Info.DiagnoseAbstractType();
4598 }
4599};
4600
4601void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4602 Sema::AbstractDiagSelID Sel) {
4603 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4604}
4605
4606}
4607
4608/// Check for invalid uses of an abstract type in a method declaration.
4609static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4610 CXXMethodDecl *MD) {
4611 // No need to do the check on definitions, which require that
4612 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004613 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004614 return;
4615
4616 // For safety's sake, just ignore it if we don't have type source
4617 // information. This should never happen for non-implicit methods,
4618 // but...
4619 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4620 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4621}
4622
4623/// Check for invalid uses of an abstract type within a class definition.
4624static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4625 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004626 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004627 if (D->isImplicit()) continue;
4628
4629 // Methods and method templates.
4630 if (isa<CXXMethodDecl>(D)) {
4631 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4632 } else if (isa<FunctionTemplateDecl>(D)) {
4633 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4634 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4635
4636 // Fields and static variables.
4637 } else if (isa<FieldDecl>(D)) {
4638 FieldDecl *FD = cast<FieldDecl>(D);
4639 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4640 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4641 } else if (isa<VarDecl>(D)) {
4642 VarDecl *VD = cast<VarDecl>(D);
4643 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4644 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4645
4646 // Nested classes and class templates.
4647 } else if (isa<CXXRecordDecl>(D)) {
4648 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4649 } else if (isa<ClassTemplateDecl>(D)) {
4650 CheckAbstractClassUsage(Info,
4651 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4652 }
4653 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004654}
4655
Hans Wennborg853ae942014-05-30 16:59:42 +00004656/// \brief Check class-level dllimport/dllexport attribute.
4657static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4658 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004659
4660 // MSVC inherits DLL attributes to partial class template specializations.
4661 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4662 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4663 if (Attr *TemplateAttr =
4664 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4665 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4666 A->setInherited(true);
4667 ClassAttr = A;
4668 }
4669 }
4670 }
4671
Hans Wennborg853ae942014-05-30 16:59:42 +00004672 if (!ClassAttr)
4673 return;
4674
Hans Wennborg8313c762014-11-03 16:09:16 +00004675 if (!Class->isExternallyVisible()) {
4676 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4677 << Class << ClassAttr;
4678 return;
4679 }
4680
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004681 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4682 !ClassAttr->isInherited()) {
4683 // Diagnose dll attributes on members of class with dll attribute.
4684 for (Decl *Member : Class->decls()) {
4685 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4686 continue;
4687 InheritableAttr *MemberAttr = getDLLAttr(Member);
4688 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4689 continue;
4690
4691 S.Diag(MemberAttr->getLocation(),
4692 diag::err_attribute_dll_member_of_dll_class)
4693 << MemberAttr << ClassAttr;
4694 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4695 Member->setInvalidDecl();
4696 }
4697 }
4698
4699 if (Class->getDescribedClassTemplate())
4700 // Don't inherit dll attribute until the template is instantiated.
4701 return;
4702
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004703 // The class is either imported or exported.
4704 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4705 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004706
4707 // Force declaration of implicit members so they can inherit the attribute.
4708 S.ForceDeclarationOfImplicitMembers(Class);
4709
4710 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4711 // seem to be true in practice?
4712
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004713 TemplateSpecializationKind TSK =
4714 Class->getTemplateSpecializationKind();
4715
Hans Wennborg853ae942014-05-30 16:59:42 +00004716 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004717 VarDecl *VD = dyn_cast<VarDecl>(Member);
4718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4719
4720 // Only methods and static fields inherit the attributes.
4721 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004722 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004723
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004724 if (MD) {
4725 // Don't process deleted methods.
4726 if (MD->isDeleted())
4727 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004728
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004729 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4730 // Current MSVC versions don't export the move assignment operators, so
4731 // don't attempt to import them if we have a definition.
4732 continue;
4733 }
4734
4735 if (MD->isInlined() && ClassImported &&
4736 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4737 // MinGW does not import inline functions.
4738 continue;
4739 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004740 }
4741
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004742 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004743 auto *NewAttr =
4744 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4745 NewAttr->setInherited(true);
4746 Member->addAttr(NewAttr);
4747 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004748
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004749 if (MD && ClassExported) {
4750 if (MD->isUserProvided()) {
4751 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004752
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004753 // .. except for certain kinds of template specializations.
4754 if (TSK == TSK_ExplicitInstantiationDeclaration)
4755 continue;
4756 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4757 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004758
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004759 S.MarkFunctionReferenced(Class->getLocation(), MD);
4760 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4761 MD->isCopyAssignmentOperator() ||
4762 MD->isMoveAssignmentOperator()) {
4763 // Instantiate non-trivial or explicitly defaulted methods, and the
4764 // copy assignment / move assignment operators.
4765 S.MarkFunctionReferenced(Class->getLocation(), MD);
4766 // Resolve its exception specification; CodeGen needs it.
4767 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4768 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4769 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004770 }
4771 }
4772 }
4773}
4774
Douglas Gregorc99f1552009-12-03 18:33:45 +00004775/// \brief Perform semantic checks on a class definition that has been
4776/// completing, introducing implicitly-declared members, checking for
4777/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004778void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004779 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004780 return;
4781
John McCall02db245d2010-08-18 09:41:07 +00004782 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4783 AbstractUsageInfo Info(*this, Record);
4784 CheckAbstractClassUsage(Info, Record);
4785 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004786
4787 // If this is not an aggregate type and has no user-declared constructor,
4788 // complain about any non-static data members of reference or const scalar
4789 // type, since they will never get initializers.
4790 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004791 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4792 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004793 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004794 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004795 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004796 continue;
4797
Douglas Gregor454a5b62010-04-15 00:00:53 +00004798 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004799 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004800 if (!Complained) {
4801 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4802 << Record->getTagKind() << Record;
4803 Complained = true;
4804 }
4805
4806 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4807 << F->getType()->isReferenceType()
4808 << F->getDeclName();
4809 }
4810 }
4811 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004812
Anders Carlssone771e762011-01-25 18:08:22 +00004813 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004814 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004815
4816 if (Record->getIdentifier()) {
4817 // C++ [class.mem]p13:
4818 // If T is the name of a class, then each of the following shall have a
4819 // name different from T:
4820 // - every member of every anonymous union that is a member of class T.
4821 //
4822 // C++ [class.mem]p14:
4823 // In addition, if class T has a user-declared constructor (12.1), every
4824 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004825 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4826 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4827 ++I) {
4828 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004829 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4830 isa<IndirectFieldDecl>(D)) {
4831 Diag(D->getLocation(), diag::err_member_name_of_class)
4832 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004833 break;
4834 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004835 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004836 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004837
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004838 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004839 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004840 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004841 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4842 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004843 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4844 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4845 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004846
David Majnemera5433082013-10-18 00:33:31 +00004847 if (Record->isAbstract()) {
4848 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4849 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4850 << FA->isSpelledAsSealed();
4851 DiagnoseAbstractType(Record);
4852 }
David Blaikie348df502012-09-21 03:21:07 +00004853 }
4854
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004855 bool HasMethodWithOverrideControl = false,
4856 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004857 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004858 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004859 // See if a method overloads virtual methods in a base
4860 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004861 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004862 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004863 if (M->hasAttr<OverrideAttr>())
4864 HasMethodWithOverrideControl = true;
4865 else if (M->size_overridden_methods() > 0)
4866 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004867 // Check whether the explicitly-defaulted special members are valid.
4868 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004869 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004870
4871 // For an explicitly defaulted or deleted special member, we defer
4872 // determining triviality until the class is complete. That time is now!
4873 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004874 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004875 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004876 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004877
4878 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004879 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004880 }
4881 }
4882 }
4883 }
4884
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004885 if (HasMethodWithOverrideControl &&
4886 HasOverridingMethodWithoutOverrideControl) {
4887 // At least one method has the 'override' control declared.
4888 // Diagnose all other overridden methods which do not have 'override' specified on them.
4889 for (auto *M : Record->methods())
4890 DiagnoseAbsenceOfOverrideControl(M);
4891 }
Richard Smithbd305122012-12-11 01:14:52 +00004892 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4893 // function that is not a constructor declares that member function to be
4894 // const. [...] The class of which that function is a member shall be
4895 // a literal type.
4896 //
4897 // If the class has virtual bases, any constexpr members will already have
4898 // been diagnosed by the checks performed on the member declaration, so
4899 // suppress this (less useful) diagnostic.
4900 //
4901 // We delay this until we know whether an explicitly-defaulted (or deleted)
4902 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004903 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004904 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004905 for (const auto *M : Record->methods()) {
4906 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004907 switch (Record->getTemplateSpecializationKind()) {
4908 case TSK_ImplicitInstantiation:
4909 case TSK_ExplicitInstantiationDeclaration:
4910 case TSK_ExplicitInstantiationDefinition:
4911 // If a template instantiates to a non-literal type, but its members
4912 // instantiate to constexpr functions, the template is technically
4913 // ill-formed, but we allow it for sanity.
4914 continue;
4915
4916 case TSK_Undeclared:
4917 case TSK_ExplicitSpecialization:
4918 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4919 diag::err_constexpr_method_non_literal);
4920 break;
4921 }
4922
4923 // Only produce one error per class.
4924 break;
4925 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004926 }
4927 }
Sebastian Redl08905022011-02-05 19:23:19 +00004928
John McCall95833f32014-02-27 20:30:49 +00004929 // ms_struct is a request to use the same ABI rules as MSVC. Check
4930 // whether this class uses any C++ features that are implemented
4931 // completely differently in MSVC, and if so, emit a diagnostic.
4932 // That diagnostic defaults to an error, but we allow projects to
4933 // map it down to a warning (or ignore it). It's a fairly common
4934 // practice among users of the ms_struct pragma to mass-annotate
4935 // headers, sweeping up a bunch of types that the project doesn't
4936 // really rely on MSVC-compatible layout for. We must therefore
4937 // support "ms_struct except for C++ stuff" as a secondary ABI.
4938 if (Record->isMsStruct(Context) &&
4939 (Record->isPolymorphic() || Record->getNumBases())) {
4940 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004941 }
4942
Richard Smithc2bc61b2013-03-18 21:12:30 +00004943 // Declare inheriting constructors. We do this eagerly here because:
4944 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004945 // constructors from different classes.
4946 // - The lazy declaration of the other implicit constructors is so as to not
4947 // waste space and performance on classes that are not meant to be
4948 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004949 // have inheriting constructors.
4950 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004951
4952 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004953}
4954
Richard Smith41c35d62013-11-27 03:39:20 +00004955/// Look up the special member function that would be called by a special
4956/// member function for a subobject of class type.
4957///
4958/// \param Class The class type of the subobject.
4959/// \param CSM The kind of special member function.
4960/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4961/// \param ConstRHS True if this is a copy operation with a const object
4962/// on its RHS, that is, if the argument to the outer special member
4963/// function is 'const' and this is not a field marked 'mutable'.
4964static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4965 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4966 unsigned FieldQuals, bool ConstRHS) {
4967 unsigned LHSQuals = 0;
4968 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4969 LHSQuals = FieldQuals;
4970
4971 unsigned RHSQuals = FieldQuals;
4972 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4973 RHSQuals = 0;
4974 else if (ConstRHS)
4975 RHSQuals |= Qualifiers::Const;
4976
4977 return S.LookupSpecialMember(Class, CSM,
4978 RHSQuals & Qualifiers::Const,
4979 RHSQuals & Qualifiers::Volatile,
4980 false,
4981 LHSQuals & Qualifiers::Const,
4982 LHSQuals & Qualifiers::Volatile);
4983}
4984
Richard Smithb5800092012-06-10 05:43:50 +00004985/// Is the special member function which would be selected to perform the
4986/// specified operation on the specified class type a constexpr constructor?
4987static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4988 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004989 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004990 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004991 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004992 if (!SMOR || !SMOR->getMethod())
4993 // A constructor we wouldn't select can't be "involved in initializing"
4994 // anything.
4995 return true;
4996 return SMOR->getMethod()->isConstexpr();
4997}
4998
4999/// Determine whether the specified special member function would be constexpr
5000/// if it were implicitly defined.
5001static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5002 Sema::CXXSpecialMember CSM,
5003 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005004 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005005 return false;
5006
5007 // C++11 [dcl.constexpr]p4:
5008 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005009 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005010 switch (CSM) {
5011 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005012 // Since default constructor lookup is essentially trivial (and cannot
5013 // involve, for instance, template instantiation), we compute whether a
5014 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5015 //
5016 // This is important for performance; we need to know whether the default
5017 // constructor is constexpr to determine whether the type is a literal type.
5018 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5019
Richard Smithb5800092012-06-10 05:43:50 +00005020 case Sema::CXXCopyConstructor:
5021 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005022 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005023 break;
5024
5025 case Sema::CXXCopyAssignment:
5026 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005027 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005028 return false;
5029 // In C++1y, we need to perform overload resolution.
5030 Ctor = false;
5031 break;
5032
Richard Smithb5800092012-06-10 05:43:50 +00005033 case Sema::CXXDestructor:
5034 case Sema::CXXInvalid:
5035 return false;
5036 }
5037
5038 // -- if the class is a non-empty union, or for each non-empty anonymous
5039 // union member of a non-union class, exactly one non-static data member
5040 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005041 //
5042 // If we squint, this is guaranteed, since exactly one non-static data member
5043 // will be initialized (if the constructor isn't deleted), we just don't know
5044 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005045 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005046 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005047
5048 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005049 if (Ctor && ClassDecl->getNumVBases())
5050 return false;
5051
5052 // C++1y [class.copy]p26:
5053 // -- [the class] is a literal type, and
5054 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005055 return false;
5056
5057 // -- every constructor involved in initializing [...] base class
5058 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005059 // -- the assignment operator selected to copy/move each direct base
5060 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005061 for (const auto &B : ClassDecl->bases()) {
5062 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005063 if (!BaseType) continue;
5064
5065 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005066 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005067 return false;
5068 }
5069
5070 // -- every constructor involved in initializing non-static data members
5071 // [...] shall be a constexpr constructor;
5072 // -- every non-static data member and base class sub-object shall be
5073 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005074 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005075 // thereof), the assignment operator selected to copy/move that member is
5076 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005077 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005078 if (F->isInvalidDecl())
5079 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005080 QualType BaseType = S.Context.getBaseElementType(F->getType());
5081 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005082 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005083 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5084 BaseType.getCVRQualifiers(),
5085 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005086 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005087 }
5088 }
5089
5090 // All OK, it's constexpr!
5091 return true;
5092}
5093
Richard Smithd3b5c9082012-07-27 04:22:15 +00005094static Sema::ImplicitExceptionSpecification
5095computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5096 switch (S.getSpecialMember(MD)) {
5097 case Sema::CXXDefaultConstructor:
5098 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5099 case Sema::CXXCopyConstructor:
5100 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5101 case Sema::CXXCopyAssignment:
5102 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5103 case Sema::CXXMoveConstructor:
5104 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5105 case Sema::CXXMoveAssignment:
5106 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5107 case Sema::CXXDestructor:
5108 return S.ComputeDefaultedDtorExceptionSpec(MD);
5109 case Sema::CXXInvalid:
5110 break;
5111 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005112 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5113 "only special members have implicit exception specs");
5114 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005115}
5116
Reid Kleckner78af0702013-08-27 23:08:25 +00005117static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5118 CXXMethodDecl *MD) {
5119 FunctionProtoType::ExtProtoInfo EPI;
5120
5121 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005122 EPI.ExceptionSpec.Type = EST_Unevaluated;
5123 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005124
5125 // Set the calling convention to the default for C++ instance methods.
5126 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5127 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5128 /*IsCXXMethod=*/true));
5129 return EPI;
5130}
5131
Richard Smithd3b5c9082012-07-27 04:22:15 +00005132void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5133 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5134 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5135 return;
5136
Richard Smith7f782272012-07-30 23:48:14 +00005137 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005138 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005139
Richard Smith7f782272012-07-30 23:48:14 +00005140 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005141 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005142
5143 // A user-provided destructor can be defined outside the class. When that
5144 // happens, be sure to update the exception specification on both
5145 // declarations.
5146 const FunctionProtoType *CanonicalFPT =
5147 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5148 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005149 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005150}
5151
Richard Smithb9e90b12012-05-15 04:39:51 +00005152void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5153 CXXRecordDecl *RD = MD->getParent();
5154 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005155
Richard Smithb9e90b12012-05-15 04:39:51 +00005156 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5157 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005158
5159 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005160 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005161 bool First = MD == MD->getCanonicalDecl();
5162
5163 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005164
5165 // C++11 [dcl.fct.def.default]p1:
5166 // A function that is explicitly defaulted shall
5167 // -- be a special member function (checked elsewhere),
5168 // -- have the same type (except for ref-qualifiers, and except that a
5169 // copy operation can take a non-const reference) as an implicit
5170 // declaration, and
5171 // -- not have default arguments.
5172 unsigned ExpectedParams = 1;
5173 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5174 ExpectedParams = 0;
5175 if (MD->getNumParams() != ExpectedParams) {
5176 // This also checks for default arguments: a copy or move constructor with a
5177 // default argument is classified as a default constructor, and assignment
5178 // operations and destructors can't have default arguments.
5179 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5180 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005181 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005182 } else if (MD->isVariadic()) {
5183 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5184 << CSM << MD->getSourceRange();
5185 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005186 }
5187
Richard Smithb9e90b12012-05-15 04:39:51 +00005188 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005189
Richard Smithb5800092012-06-10 05:43:50 +00005190 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005191 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005192 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005193 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005194 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005195
Richard Smithb9e90b12012-05-15 04:39:51 +00005196 QualType ReturnType = Context.VoidTy;
5197 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5198 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005199 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005200 QualType ExpectedReturnType =
5201 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5202 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5203 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5204 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5205 HadError = true;
5206 }
5207
5208 // A defaulted special member cannot have cv-qualifiers.
5209 if (Type->getTypeQuals()) {
5210 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005211 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005212 HadError = true;
5213 }
5214 }
5215
5216 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005217 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005218 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005219 if (ExpectedParams && ArgType->isReferenceType()) {
5220 // Argument must be reference to possibly-const T.
5221 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005222 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005223
5224 if (ReferentType.isVolatileQualified()) {
5225 Diag(MD->getLocation(),
5226 diag::err_defaulted_special_member_volatile_param) << CSM;
5227 HadError = true;
5228 }
5229
Richard Smithb5800092012-06-10 05:43:50 +00005230 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005231 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5232 Diag(MD->getLocation(),
5233 diag::err_defaulted_special_member_copy_const_param)
5234 << (CSM == CXXCopyAssignment);
5235 // FIXME: Explain why this special member can't be const.
5236 } else {
5237 Diag(MD->getLocation(),
5238 diag::err_defaulted_special_member_move_const_param)
5239 << (CSM == CXXMoveAssignment);
5240 }
5241 HadError = true;
5242 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005243 } else if (ExpectedParams) {
5244 // A copy assignment operator can take its argument by value, but a
5245 // defaulted one cannot.
5246 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005247 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005248 HadError = true;
5249 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005250
Richard Smithcc36f692011-12-22 02:22:31 +00005251 // C++11 [dcl.fct.def.default]p2:
5252 // An explicitly-defaulted function may be declared constexpr only if it
5253 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005254 // Do not apply this rule to members of class templates, since core issue 1358
5255 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005256 // functions which cannot be constexpr (for non-constructors in C++11 and for
5257 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005258 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5259 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005260 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005261 : isa<CXXConstructorDecl>(MD)) &&
5262 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005263 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5264 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005265 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005266 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005267 }
Richard Smithbd305122012-12-11 01:14:52 +00005268
Richard Smithcc36f692011-12-22 02:22:31 +00005269 // and may have an explicit exception-specification only if it is compatible
5270 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005271 if (Type->hasExceptionSpec()) {
5272 // Delay the check if this is the first declaration of the special member,
5273 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005274 if (First) {
5275 // If the exception specification needs to be instantiated, do so now,
5276 // before we clobber it with an EST_Unevaluated specification below.
5277 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5278 InstantiateExceptionSpec(MD->getLocStart(), MD);
5279 Type = MD->getType()->getAs<FunctionProtoType>();
5280 }
Richard Smithbd305122012-12-11 01:14:52 +00005281 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005282 } else
Richard Smithbd305122012-12-11 01:14:52 +00005283 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5284 }
Richard Smithcc36f692011-12-22 02:22:31 +00005285
5286 // If a function is explicitly defaulted on its first declaration,
5287 if (First) {
5288 // -- it is implicitly considered to be constexpr if the implicit
5289 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005290 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005291
Richard Smithb9e90b12012-05-15 04:39:51 +00005292 // -- it is implicitly considered to have the same exception-specification
5293 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005294 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005295 EPI.ExceptionSpec.Type = EST_Unevaluated;
5296 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005297 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005298 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005299 ExpectedParams),
5300 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005301 }
5302
Richard Smithb9e90b12012-05-15 04:39:51 +00005303 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005304 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005305 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005306 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005307 // C++11 [dcl.fct.def.default]p4:
5308 // [For a] user-provided explicitly-defaulted function [...] if such a
5309 // function is implicitly defined as deleted, the program is ill-formed.
5310 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005311 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005312 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005313 }
5314 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005315
Richard Smithb9e90b12012-05-15 04:39:51 +00005316 if (HadError)
5317 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005318}
5319
Richard Smithbd305122012-12-11 01:14:52 +00005320/// Check whether the exception specification provided for an
5321/// explicitly-defaulted special member matches the exception specification
5322/// that would have been generated for an implicit special member, per
5323/// C++11 [dcl.fct.def.default]p2.
5324void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5325 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005326 // If the exception specification was explicitly specified but hadn't been
5327 // parsed when the method was defaulted, grab it now.
5328 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5329 SpecifiedType =
5330 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5331
Richard Smithbd305122012-12-11 01:14:52 +00005332 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005333 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5334 /*IsCXXMethod=*/true);
5335 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005336 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5337 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005338 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005339 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005340
5341 // Ensure that it matches.
5342 CheckEquivalentExceptionSpec(
5343 PDiag(diag::err_incorrect_defaulted_exception_spec)
5344 << getSpecialMember(MD), PDiag(),
5345 ImplicitType, SourceLocation(),
5346 SpecifiedType, MD->getLocation());
5347}
5348
Alp Tokerae3a9442013-10-18 05:54:19 +00005349void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005350 decltype(DelayedExceptionSpecChecks) Checks;
5351 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005352
Richard Smith88f45492014-11-22 03:09:05 +00005353 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005354 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5355
5356 // Perform any deferred checking of exception specifications for virtual
5357 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005358 for (auto &Check : Checks)
5359 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005360
5361 // Check that any explicitly-defaulted methods have exception specifications
5362 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005363 for (auto &Spec : Specs)
5364 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005365}
5366
Richard Smithd951a1d2012-02-18 02:02:13 +00005367namespace {
5368struct SpecialMemberDeletionInfo {
5369 Sema &S;
5370 CXXMethodDecl *MD;
5371 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005372 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005373
5374 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005375 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005376 SourceLocation Loc;
5377
5378 bool AllFieldsAreConst;
5379
5380 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005381 Sema::CXXSpecialMember CSM, bool Diagnose)
5382 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005383 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005384 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005385 AllFieldsAreConst(true) {
5386 switch (CSM) {
5387 case Sema::CXXDefaultConstructor:
5388 case Sema::CXXCopyConstructor:
5389 IsConstructor = true;
5390 break;
5391 case Sema::CXXMoveConstructor:
5392 IsConstructor = true;
5393 IsMove = true;
5394 break;
5395 case Sema::CXXCopyAssignment:
5396 IsAssignment = true;
5397 break;
5398 case Sema::CXXMoveAssignment:
5399 IsAssignment = true;
5400 IsMove = true;
5401 break;
5402 case Sema::CXXDestructor:
5403 break;
5404 case Sema::CXXInvalid:
5405 llvm_unreachable("invalid special member kind");
5406 }
5407
5408 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005409 if (const ReferenceType *RT =
5410 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5411 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005412 }
5413 }
5414
5415 bool inUnion() const { return MD->getParent()->isUnion(); }
5416
5417 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005418 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005419 unsigned Quals, bool IsMutable) {
5420 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5421 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005422 }
5423
Richard Smith852265f2012-03-30 20:53:28 +00005424 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005425
Richard Smith852265f2012-03-30 20:53:28 +00005426 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005427 bool shouldDeleteForField(FieldDecl *FD);
5428 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005429
Richard Smithaf136f82012-07-18 03:51:16 +00005430 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5431 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005432 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5433 Sema::SpecialMemberOverloadResult *SMOR,
5434 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005435
5436 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005437};
5438}
5439
John McCalld4274212012-04-09 20:53:23 +00005440/// Is the given special member inaccessible when used on the given
5441/// sub-object.
5442bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5443 CXXMethodDecl *target) {
5444 /// If we're operating on a base class, the object type is the
5445 /// type of this special member.
5446 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005447 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005448 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5449 objectTy = S.Context.getTypeDeclType(MD->getParent());
5450 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5451
5452 // If we're operating on a field, the object type is the type of the field.
5453 } else {
5454 objectTy = S.Context.getTypeDeclType(target->getParent());
5455 }
5456
5457 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5458}
5459
Richard Smith852265f2012-03-30 20:53:28 +00005460/// Check whether we should delete a special member due to the implicit
5461/// definition containing a call to a special member of a subobject.
5462bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5463 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5464 bool IsDtorCallInCtor) {
5465 CXXMethodDecl *Decl = SMOR->getMethod();
5466 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5467
5468 int DiagKind = -1;
5469
5470 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5471 DiagKind = !Decl ? 0 : 1;
5472 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5473 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005474 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005475 DiagKind = 3;
5476 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5477 !Decl->isTrivial()) {
5478 // A member of a union must have a trivial corresponding special member.
5479 // As a weird special case, a destructor call from a union's constructor
5480 // must be accessible and non-deleted, but need not be trivial. Such a
5481 // destructor is never actually called, but is semantically checked as
5482 // if it were.
5483 DiagKind = 4;
5484 }
5485
5486 if (DiagKind == -1)
5487 return false;
5488
5489 if (Diagnose) {
5490 if (Field) {
5491 S.Diag(Field->getLocation(),
5492 diag::note_deleted_special_member_class_subobject)
5493 << CSM << MD->getParent() << /*IsField*/true
5494 << Field << DiagKind << IsDtorCallInCtor;
5495 } else {
5496 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5497 S.Diag(Base->getLocStart(),
5498 diag::note_deleted_special_member_class_subobject)
5499 << CSM << MD->getParent() << /*IsField*/false
5500 << Base->getType() << DiagKind << IsDtorCallInCtor;
5501 }
5502
5503 if (DiagKind == 1)
5504 S.NoteDeletedFunction(Decl);
5505 // FIXME: Explain inaccessibility if DiagKind == 3.
5506 }
5507
5508 return true;
5509}
5510
Richard Smith921bd202012-02-26 09:11:52 +00005511/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005512/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005513bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005514 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005515 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005516 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005517
5518 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005519 // -- any direct or virtual base class, or non-static data member with no
5520 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005521 // either M has no default constructor or overload resolution as applied
5522 // to M's default constructor results in an ambiguity or in a function
5523 // that is deleted or inaccessible
5524 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5525 // -- a direct or virtual base class B that cannot be copied/moved because
5526 // overload resolution, as applied to B's corresponding special member,
5527 // results in an ambiguity or a function that is deleted or inaccessible
5528 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005529 // C++11 [class.dtor]p5:
5530 // -- any direct or virtual base class [...] has a type with a destructor
5531 // that is deleted or inaccessible
5532 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005533 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005534 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5535 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005536 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005537
Richard Smith852265f2012-03-30 20:53:28 +00005538 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5539 // -- any direct or virtual base class or non-static data member has a
5540 // type with a destructor that is deleted or inaccessible
5541 if (IsConstructor) {
5542 Sema::SpecialMemberOverloadResult *SMOR =
5543 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5544 false, false, false, false, false);
5545 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5546 return true;
5547 }
5548
Richard Smith921bd202012-02-26 09:11:52 +00005549 return false;
5550}
5551
5552/// Check whether we should delete a special member function due to the class
5553/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005554bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005555 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005556 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005557}
5558
5559/// Check whether we should delete a special member function due to the class
5560/// having a particular non-static data member.
5561bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5562 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5563 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5564
5565 if (CSM == Sema::CXXDefaultConstructor) {
5566 // For a default constructor, all references must be initialized in-class
5567 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005568 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5569 if (Diagnose)
5570 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5571 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005572 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005573 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005574 // C++11 [class.ctor]p5: any non-variant non-static data member of
5575 // const-qualified type (or array thereof) with no
5576 // brace-or-equal-initializer does not have a user-provided default
5577 // constructor.
5578 if (!inUnion() && FieldType.isConstQualified() &&
5579 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005580 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5581 if (Diagnose)
5582 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005583 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005584 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005585 }
5586
5587 if (inUnion() && !FieldType.isConstQualified())
5588 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005589 } else if (CSM == Sema::CXXCopyConstructor) {
5590 // For a copy constructor, data members must not be of rvalue reference
5591 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005592 if (FieldType->isRValueReferenceType()) {
5593 if (Diagnose)
5594 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5595 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005596 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005597 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005598 } else if (IsAssignment) {
5599 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005600 if (FieldType->isReferenceType()) {
5601 if (Diagnose)
5602 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5603 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005604 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005605 }
5606 if (!FieldRecord && FieldType.isConstQualified()) {
5607 // C++11 [class.copy]p23:
5608 // -- a non-static data member of const non-class type (or array thereof)
5609 if (Diagnose)
5610 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005611 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005612 return true;
5613 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005614 }
5615
5616 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005617 // Some additional restrictions exist on the variant members.
5618 if (!inUnion() && FieldRecord->isUnion() &&
5619 FieldRecord->isAnonymousStructOrUnion()) {
5620 bool AllVariantFieldsAreConst = true;
5621
Richard Smith5704fe82012-03-29 19:00:10 +00005622 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005623 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005624 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005625
5626 if (!UnionFieldType.isConstQualified())
5627 AllVariantFieldsAreConst = false;
5628
Richard Smith921bd202012-02-26 09:11:52 +00005629 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5630 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005631 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005632 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005633 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005634 }
5635
5636 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005637 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005638 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005639 if (Diagnose)
5640 S.Diag(FieldRecord->getLocation(),
5641 diag::note_deleted_default_ctor_all_const)
5642 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005643 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005644 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005645
Richard Smith5704fe82012-03-29 19:00:10 +00005646 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005647 // This is technically non-conformant, but sanity demands it.
5648 return false;
5649 }
5650
Richard Smithaf136f82012-07-18 03:51:16 +00005651 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5652 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005653 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005654 }
5655
5656 return false;
5657}
5658
5659/// C++11 [class.ctor] p5:
5660/// A defaulted default constructor for a class X is defined as deleted if
5661/// X is a union and all of its variant members are of const-qualified type.
5662bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005663 // This is a silly definition, because it gives an empty union a deleted
5664 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005665 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005666 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005667 if (Diagnose)
5668 S.Diag(MD->getParent()->getLocation(),
5669 diag::note_deleted_default_ctor_all_const)
5670 << MD->getParent() << /*not anonymous union*/0;
5671 return true;
5672 }
5673 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005674}
5675
5676/// Determine whether a defaulted special member function should be defined as
5677/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5678/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005679bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5680 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005681 if (MD->isInvalidDecl())
5682 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005683 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005684 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005685 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005686 return false;
5687
Richard Smithd951a1d2012-02-18 02:02:13 +00005688 // C++11 [expr.lambda.prim]p19:
5689 // The closure type associated with a lambda-expression has a
5690 // deleted (8.4.3) default constructor and a deleted copy
5691 // assignment operator.
5692 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005693 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5694 if (Diagnose)
5695 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005696 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005697 }
5698
Richard Smith6f1e2c62012-04-02 20:59:25 +00005699 // For an anonymous struct or union, the copy and assignment special members
5700 // will never be used, so skip the check. For an anonymous union declared at
5701 // namespace scope, the constructor and destructor are used.
5702 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5703 RD->isAnonymousStructOrUnion())
5704 return false;
5705
Richard Smith852265f2012-03-30 20:53:28 +00005706 // C++11 [class.copy]p7, p18:
5707 // If the class definition declares a move constructor or move assignment
5708 // operator, an implicitly declared copy constructor or copy assignment
5709 // operator is defined as deleted.
5710 if (MD->isImplicit() &&
5711 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005712 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005713
5714 // In Microsoft mode, a user-declared move only causes the deletion of the
5715 // corresponding copy operation, not both copy operations.
5716 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005717 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005718 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005719
5720 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005721 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005722 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005723 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005724 break;
5725 }
5726 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005727 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005728 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005729 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005730 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005731
5732 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005733 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005734 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005735 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005736 break;
5737 }
5738 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005739 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005740 }
5741
5742 if (UserDeclaredMove) {
5743 Diag(UserDeclaredMove->getLocation(),
5744 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005745 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005746 << UserDeclaredMove->isMoveAssignmentOperator();
5747 return true;
5748 }
5749 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005750
Richard Smith6f1e2c62012-04-02 20:59:25 +00005751 // Do access control from the special member function
5752 ContextRAII MethodContext(*this, MD);
5753
Richard Smith921bd202012-02-26 09:11:52 +00005754 // C++11 [class.dtor]p5:
5755 // -- for a virtual destructor, lookup of the non-array deallocation function
5756 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005757 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005758 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005759 DeclarationName Name =
5760 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5761 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005762 OperatorDelete, false)) {
5763 if (Diagnose)
5764 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005765 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005766 }
Richard Smith921bd202012-02-26 09:11:52 +00005767 }
5768
Richard Smith852265f2012-03-30 20:53:28 +00005769 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005770
Aaron Ballman574705e2014-03-13 15:41:46 +00005771 for (auto &BI : RD->bases())
5772 if (!BI.isVirtual() &&
5773 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005774 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005775
Richard Smithd1627032013-07-22 18:06:23 +00005776 // Per DR1611, do not consider virtual bases of constructors of abstract
5777 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005778 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005779 for (auto &BI : RD->vbases())
5780 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005781 return true;
5782 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005783
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005784 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005785 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005786 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005787 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005788
Richard Smithd951a1d2012-02-18 02:02:13 +00005789 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005790 return true;
5791
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005792 if (getLangOpts().CUDA) {
5793 // We should delete the special member in CUDA mode if target inference
5794 // failed.
5795 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5796 Diagnose);
5797 }
5798
Alexis Huntea6f0322011-05-11 22:34:38 +00005799 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005800}
5801
Richard Smith92f241f2012-12-08 02:53:02 +00005802/// Perform lookup for a special member of the specified kind, and determine
5803/// whether it is trivial. If the triviality can be determined without the
5804/// lookup, skip it. This is intended for use when determining whether a
5805/// special member of a containing object is trivial, and thus does not ever
5806/// perform overload resolution for default constructors.
5807///
5808/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5809/// member that was most likely to be intended to be trivial, if any.
5810static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5811 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005812 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005813 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005814 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005815
5816 switch (CSM) {
5817 case Sema::CXXInvalid:
5818 llvm_unreachable("not a special member");
5819
5820 case Sema::CXXDefaultConstructor:
5821 // C++11 [class.ctor]p5:
5822 // A default constructor is trivial if:
5823 // - all the [direct subobjects] have trivial default constructors
5824 //
5825 // Note, no overload resolution is performed in this case.
5826 if (RD->hasTrivialDefaultConstructor())
5827 return true;
5828
5829 if (Selected) {
5830 // If there's a default constructor which could have been trivial, dig it
5831 // out. Otherwise, if there's any user-provided default constructor, point
5832 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005833 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005834 if (RD->needsImplicitDefaultConstructor())
5835 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005836 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005837 if (!CI->isDefaultConstructor())
5838 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005839 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005840 if (!DefCtor->isUserProvided())
5841 break;
5842 }
5843
5844 *Selected = DefCtor;
5845 }
5846
5847 return false;
5848
5849 case Sema::CXXDestructor:
5850 // C++11 [class.dtor]p5:
5851 // A destructor is trivial if:
5852 // - all the direct [subobjects] have trivial destructors
5853 if (RD->hasTrivialDestructor())
5854 return true;
5855
5856 if (Selected) {
5857 if (RD->needsImplicitDestructor())
5858 S.DeclareImplicitDestructor(RD);
5859 *Selected = RD->getDestructor();
5860 }
5861
5862 return false;
5863
5864 case Sema::CXXCopyConstructor:
5865 // C++11 [class.copy]p12:
5866 // A copy constructor is trivial if:
5867 // - the constructor selected to copy each direct [subobject] is trivial
5868 if (RD->hasTrivialCopyConstructor()) {
5869 if (Quals == Qualifiers::Const)
5870 // We must either select the trivial copy constructor or reach an
5871 // ambiguity; no need to actually perform overload resolution.
5872 return true;
5873 } else if (!Selected) {
5874 return false;
5875 }
5876 // In C++98, we are not supposed to perform overload resolution here, but we
5877 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5878 // cases like B as having a non-trivial copy constructor:
5879 // struct A { template<typename T> A(T&); };
5880 // struct B { mutable A a; };
5881 goto NeedOverloadResolution;
5882
5883 case Sema::CXXCopyAssignment:
5884 // C++11 [class.copy]p25:
5885 // A copy assignment operator is trivial if:
5886 // - the assignment operator selected to copy each direct [subobject] is
5887 // trivial
5888 if (RD->hasTrivialCopyAssignment()) {
5889 if (Quals == Qualifiers::Const)
5890 return true;
5891 } else if (!Selected) {
5892 return false;
5893 }
5894 // In C++98, we are not supposed to perform overload resolution here, but we
5895 // treat that as a language defect.
5896 goto NeedOverloadResolution;
5897
5898 case Sema::CXXMoveConstructor:
5899 case Sema::CXXMoveAssignment:
5900 NeedOverloadResolution:
5901 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005902 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005903
5904 // The standard doesn't describe how to behave if the lookup is ambiguous.
5905 // We treat it as not making the member non-trivial, just like the standard
5906 // mandates for the default constructor. This should rarely matter, because
5907 // the member will also be deleted.
5908 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5909 return true;
5910
5911 if (!SMOR->getMethod()) {
5912 assert(SMOR->getKind() ==
5913 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5914 return false;
5915 }
5916
5917 // We deliberately don't check if we found a deleted special member. We're
5918 // not supposed to!
5919 if (Selected)
5920 *Selected = SMOR->getMethod();
5921 return SMOR->getMethod()->isTrivial();
5922 }
5923
5924 llvm_unreachable("unknown special method kind");
5925}
5926
Benjamin Kramer3e350262013-02-15 12:30:38 +00005927static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005928 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005929 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005930 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005931
5932 // Look for constructor templates.
5933 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5934 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5935 if (CXXConstructorDecl *CD =
5936 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5937 return CD;
5938 }
5939
Craig Topperc3ec1492014-05-26 06:22:03 +00005940 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005941}
5942
5943/// The kind of subobject we are checking for triviality. The values of this
5944/// enumeration are used in diagnostics.
5945enum TrivialSubobjectKind {
5946 /// The subobject is a base class.
5947 TSK_BaseClass,
5948 /// The subobject is a non-static data member.
5949 TSK_Field,
5950 /// The object is actually the complete object.
5951 TSK_CompleteObject
5952};
5953
5954/// Check whether the special member selected for a given type would be trivial.
5955static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005956 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005957 Sema::CXXSpecialMember CSM,
5958 TrivialSubobjectKind Kind,
5959 bool Diagnose) {
5960 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5961 if (!SubRD)
5962 return true;
5963
5964 CXXMethodDecl *Selected;
5965 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005966 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005967 return true;
5968
5969 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005970 if (ConstRHS)
5971 SubType.addConst();
5972
Richard Smith92f241f2012-12-08 02:53:02 +00005973 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5974 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5975 << Kind << SubType.getUnqualifiedType();
5976 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5977 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5978 } else if (!Selected)
5979 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5980 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5981 else if (Selected->isUserProvided()) {
5982 if (Kind == TSK_CompleteObject)
5983 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5984 << Kind << SubType.getUnqualifiedType() << CSM;
5985 else {
5986 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5987 << Kind << SubType.getUnqualifiedType() << CSM;
5988 S.Diag(Selected->getLocation(), diag::note_declared_at);
5989 }
5990 } else {
5991 if (Kind != TSK_CompleteObject)
5992 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5993 << Kind << SubType.getUnqualifiedType() << CSM;
5994
5995 // Explain why the defaulted or deleted special member isn't trivial.
5996 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5997 }
5998 }
5999
6000 return false;
6001}
6002
6003/// Check whether the members of a class type allow a special member to be
6004/// trivial.
6005static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6006 Sema::CXXSpecialMember CSM,
6007 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006008 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006009 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6010 continue;
6011
6012 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6013
6014 // Pretend anonymous struct or union members are members of this class.
6015 if (FI->isAnonymousStructOrUnion()) {
6016 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6017 CSM, ConstArg, Diagnose))
6018 return false;
6019 continue;
6020 }
6021
6022 // C++11 [class.ctor]p5:
6023 // A default constructor is trivial if [...]
6024 // -- no non-static data member of its class has a
6025 // brace-or-equal-initializer
6026 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6027 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006028 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006029 return false;
6030 }
6031
6032 // Objective C ARC 4.3.5:
6033 // [...] nontrivally ownership-qualified types are [...] not trivially
6034 // default constructible, copy constructible, move constructible, copy
6035 // assignable, move assignable, or destructible [...]
6036 if (S.getLangOpts().ObjCAutoRefCount &&
6037 FieldType.hasNonTrivialObjCLifetime()) {
6038 if (Diagnose)
6039 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6040 << RD << FieldType.getObjCLifetime();
6041 return false;
6042 }
6043
Richard Smith41c35d62013-11-27 03:39:20 +00006044 bool ConstRHS = ConstArg && !FI->isMutable();
6045 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6046 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006047 return false;
6048 }
6049
6050 return true;
6051}
6052
6053/// Diagnose why the specified class does not have a trivial special member of
6054/// the given kind.
6055void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6056 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006057
Richard Smith41c35d62013-11-27 03:39:20 +00006058 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6059 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006060 TSK_CompleteObject, /*Diagnose*/true);
6061}
6062
6063/// Determine whether a defaulted or deleted special member function is trivial,
6064/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6065/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6066bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6067 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006068 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6069
6070 CXXRecordDecl *RD = MD->getParent();
6071
6072 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006073
Richard Smith2002bfe2013-11-04 02:02:27 +00006074 // C++11 [class.copy]p12, p25: [DR1593]
6075 // A [special member] is trivial if [...] its parameter-type-list is
6076 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006077 switch (CSM) {
6078 case CXXDefaultConstructor:
6079 case CXXDestructor:
6080 // Trivial default constructors and destructors cannot have parameters.
6081 break;
6082
6083 case CXXCopyConstructor:
6084 case CXXCopyAssignment: {
6085 // Trivial copy operations always have const, non-volatile parameter types.
6086 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006087 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006088 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6089 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6090 if (Diagnose)
6091 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6092 << Param0->getSourceRange() << Param0->getType()
6093 << Context.getLValueReferenceType(
6094 Context.getRecordType(RD).withConst());
6095 return false;
6096 }
6097 break;
6098 }
6099
6100 case CXXMoveConstructor:
6101 case CXXMoveAssignment: {
6102 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006103 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006104 const RValueReferenceType *RT =
6105 Param0->getType()->getAs<RValueReferenceType>();
6106 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6107 if (Diagnose)
6108 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6109 << Param0->getSourceRange() << Param0->getType()
6110 << Context.getRValueReferenceType(Context.getRecordType(RD));
6111 return false;
6112 }
6113 break;
6114 }
6115
6116 case CXXInvalid:
6117 llvm_unreachable("not a special member");
6118 }
6119
Richard Smith92f241f2012-12-08 02:53:02 +00006120 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6121 if (Diagnose)
6122 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6123 diag::note_nontrivial_default_arg)
6124 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6125 return false;
6126 }
6127 if (MD->isVariadic()) {
6128 if (Diagnose)
6129 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6130 return false;
6131 }
6132
6133 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6134 // A copy/move [constructor or assignment operator] is trivial if
6135 // -- the [member] selected to copy/move each direct base class subobject
6136 // is trivial
6137 //
6138 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6139 // A [default constructor or destructor] is trivial if
6140 // -- all the direct base classes have trivial [default constructors or
6141 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006142 for (const auto &BI : RD->bases())
6143 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006144 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006145 return false;
6146
6147 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6148 // A copy/move [constructor or assignment operator] for a class X is
6149 // trivial if
6150 // -- for each non-static data member of X that is of class type (or array
6151 // thereof), the constructor selected to copy/move that member is
6152 // trivial
6153 //
6154 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6155 // A [default constructor or destructor] is trivial if
6156 // -- for all of the non-static data members of its class that are of class
6157 // type (or array thereof), each such class has a trivial [default
6158 // constructor or destructor]
6159 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6160 return false;
6161
6162 // C++11 [class.dtor]p5:
6163 // A destructor is trivial if [...]
6164 // -- the destructor is not virtual
6165 if (CSM == CXXDestructor && MD->isVirtual()) {
6166 if (Diagnose)
6167 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6168 return false;
6169 }
6170
6171 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6172 // A [special member] for class X is trivial if [...]
6173 // -- class X has no virtual functions and no virtual base classes
6174 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6175 if (!Diagnose)
6176 return false;
6177
6178 if (RD->getNumVBases()) {
6179 // Check for virtual bases. We already know that the corresponding
6180 // member in all bases is trivial, so vbases must all be direct.
6181 CXXBaseSpecifier &BS = *RD->vbases_begin();
6182 assert(BS.isVirtual());
6183 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6184 return false;
6185 }
6186
6187 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006188 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006189 if (MI->isVirtual()) {
6190 SourceLocation MLoc = MI->getLocStart();
6191 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6192 return false;
6193 }
6194 }
6195
6196 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6197 }
6198
6199 // Looks like it's trivial!
6200 return true;
6201}
6202
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006203/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006204namespace {
6205 struct FindHiddenVirtualMethodData {
6206 Sema *S;
6207 CXXMethodDecl *Method;
6208 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006209 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006210 };
6211}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006212
David Blaikie282c92a2012-10-19 00:53:08 +00006213/// \brief Check whether any most overriden method from MD in Methods
6214static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006215 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006216 if (MD->size_overridden_methods() == 0)
6217 return Methods.count(MD->getCanonicalDecl());
6218 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6219 E = MD->end_overridden_methods();
6220 I != E; ++I)
6221 if (CheckMostOverridenMethods(*I, Methods))
6222 return true;
6223 return false;
6224}
6225
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006226/// \brief Member lookup function that determines whether a given C++
6227/// method overloads virtual methods in a base class without overriding any,
6228/// to be used with CXXRecordDecl::lookupInBases().
6229static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6230 CXXBasePath &Path,
6231 void *UserData) {
6232 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6233
6234 FindHiddenVirtualMethodData &Data
6235 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6236
6237 DeclarationName Name = Data.Method->getDeclName();
6238 assert(Name.getNameKind() == DeclarationName::Identifier);
6239
6240 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006241 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006242 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006243 !Path.Decls.empty();
6244 Path.Decls = Path.Decls.slice(1)) {
6245 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006246 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006247 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006248 foundSameNameMethod = true;
6249 // Interested only in hidden virtual methods.
6250 if (!MD->isVirtual())
6251 continue;
6252 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006253 // don't warn about the other overloaded methods. Clang deviates from GCC
6254 // by only diagnosing overloads of inherited virtual functions that do not
6255 // override any other virtual functions in the base. GCC's
6256 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6257 // function from a base class. These cases may be better served by a
6258 // warning (not specific to virtual functions) on call sites when the call
6259 // would select a different function from the base class, were it visible.
6260 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006261 if (!Data.S->IsOverload(Data.Method, MD, false))
6262 return true;
6263 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006264 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006265 overloadedMethods.push_back(MD);
6266 }
6267 }
6268
6269 if (foundSameNameMethod)
6270 Data.OverloadedMethods.append(overloadedMethods.begin(),
6271 overloadedMethods.end());
6272 return foundSameNameMethod;
6273}
6274
David Blaikie282c92a2012-10-19 00:53:08 +00006275/// \brief Add the most overriden methods from MD to Methods
6276static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006277 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006278 if (MD->size_overridden_methods() == 0)
6279 Methods.insert(MD->getCanonicalDecl());
6280 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6281 E = MD->end_overridden_methods();
6282 I != E; ++I)
6283 AddMostOverridenMethods(*I, Methods);
6284}
6285
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006286/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006287/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006288void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6289 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006290 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006291 return;
6292
6293 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6294 /*bool RecordPaths=*/false,
6295 /*bool DetectVirtual=*/false);
6296 FindHiddenVirtualMethodData Data;
6297 Data.Method = MD;
6298 Data.S = this;
6299
6300 // Keep the base methods that were overriden or introduced in the subclass
6301 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006302 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006303 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6304 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6305 NamedDecl *ND = *I;
6306 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006307 ND = shad->getTargetDecl();
6308 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6309 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006310 }
6311
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006312 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6313 OverloadedMethods = Data.OverloadedMethods;
6314}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006315
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006316void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6317 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6318 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6319 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6320 PartialDiagnostic PD = PDiag(
6321 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6322 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6323 Diag(overloadedMD->getLocation(), PD);
6324 }
6325}
6326
6327/// \brief Diagnose methods which overload virtual methods in a base class
6328/// without overriding any.
6329void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6330 if (MD->isInvalidDecl())
6331 return;
6332
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006333 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006334 return;
6335
6336 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6337 FindHiddenVirtualMethods(MD, OverloadedMethods);
6338 if (!OverloadedMethods.empty()) {
6339 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6340 << MD << (OverloadedMethods.size() > 1);
6341
6342 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006343 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006344}
6345
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006346void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006347 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006348 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006349 SourceLocation RBrac,
6350 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006351 if (!TagDecl)
6352 return;
Mike Stump11289f42009-09-09 15:08:12 +00006353
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006354 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006355
Rafael Espindola06e1b132012-07-12 04:32:30 +00006356 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6357 if (l->getKind() != AttributeList::AT_Visibility)
6358 continue;
6359 l->setInvalid();
6360 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6361 l->getName();
6362 }
6363
David Blaikie751c5582011-09-22 02:58:26 +00006364 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006365 // strict aliasing violation!
6366 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006367 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006368
Douglas Gregor0be31a22010-07-02 17:43:08 +00006369 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006370 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006371}
6372
Douglas Gregor05379422008-11-03 17:51:48 +00006373/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6374/// special functions, such as the default constructor, copy
6375/// constructor, or destructor, to the given C++ class (C++
6376/// [special]p1). This routine can only be executed just before the
6377/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006378void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006379 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006380 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006381
Richard Smith6b02d462012-12-08 08:32:28 +00006382 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006383 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006384
Richard Smith6b02d462012-12-08 08:32:28 +00006385 // If the properties or semantics of the copy constructor couldn't be
6386 // determined while the class was being declared, force a declaration
6387 // of it now.
6388 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6389 DeclareImplicitCopyConstructor(ClassDecl);
6390 }
6391
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006392 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006393 ++ASTContext::NumImplicitMoveConstructors;
6394
Richard Smith6b02d462012-12-08 08:32:28 +00006395 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6396 DeclareImplicitMoveConstructor(ClassDecl);
6397 }
6398
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006399 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6400 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006401
6402 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006403 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006404 // it shows up in the right place in the vtable and that we diagnose
6405 // problems with the implicit exception specification.
6406 if (ClassDecl->isDynamicClass() ||
6407 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006408 DeclareImplicitCopyAssignment(ClassDecl);
6409 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006410
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006411 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006412 ++ASTContext::NumImplicitMoveAssignmentOperators;
6413
6414 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006415 if (ClassDecl->isDynamicClass() ||
6416 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006417 DeclareImplicitMoveAssignment(ClassDecl);
6418 }
6419
Douglas Gregor7454c562010-07-02 20:37:36 +00006420 if (!ClassDecl->hasUserDeclaredDestructor()) {
6421 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006422
6423 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006424 // have to declare the destructor immediately. This ensures that, e.g., it
6425 // shows up in the right place in the vtable and that we diagnose problems
6426 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006427 if (ClassDecl->isDynamicClass() ||
6428 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006429 DeclareImplicitDestructor(ClassDecl);
6430 }
Douglas Gregor05379422008-11-03 17:51:48 +00006431}
6432
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006433unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006434 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006435 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006436
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006437 // The order of template parameters is not important here. All names
6438 // get added to the same scope.
6439 SmallVector<TemplateParameterList *, 4> ParameterLists;
6440
6441 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6442 D = TD->getTemplatedDecl();
6443
6444 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6445 ParameterLists.push_back(PSD->getTemplateParameters());
6446
6447 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6448 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6449 ParameterLists.push_back(DD->getTemplateParameterList(i));
6450
6451 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6452 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6453 ParameterLists.push_back(FTD->getTemplateParameters());
6454 }
6455 }
6456
6457 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6458 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6459 ParameterLists.push_back(TD->getTemplateParameterList(i));
6460
6461 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6462 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6463 ParameterLists.push_back(CTD->getTemplateParameters());
6464 }
6465 }
6466
6467 unsigned Count = 0;
6468 for (TemplateParameterList *Params : ParameterLists) {
6469 if (Params->size() > 0)
6470 // Ignore explicit specializations; they don't contribute to the template
6471 // depth.
6472 ++Count;
6473 for (NamedDecl *Param : *Params) {
6474 if (Param->getDeclName()) {
6475 S->AddDecl(Param);
6476 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006477 }
6478 }
6479 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006480
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006481 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006482}
6483
John McCall48871652010-08-21 09:40:31 +00006484void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006485 if (!RecordD) return;
6486 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006487 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006488 PushDeclContext(S, Record);
6489}
6490
John McCall48871652010-08-21 09:40:31 +00006491void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006492 if (!RecordD) return;
6493 PopDeclContext();
6494}
6495
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006496/// This is used to implement the constant expression evaluation part of the
6497/// attribute enable_if extension. There is nothing in standard C++ which would
6498/// require reentering parameters.
6499void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6500 if (!Param)
6501 return;
6502
6503 S->AddDecl(Param);
6504 if (Param->getDeclName())
6505 IdResolver.AddDecl(Param);
6506}
6507
Douglas Gregor4d87df52008-12-16 21:30:33 +00006508/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6509/// parsing a top-level (non-nested) C++ class, and we are now
6510/// parsing those parts of the given Method declaration that could
6511/// not be parsed earlier (C++ [class.mem]p2), such as default
6512/// arguments. This action should enter the scope of the given
6513/// Method declaration as if we had just parsed the qualified method
6514/// name. However, it should not bring the parameters into scope;
6515/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006516void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006517}
6518
6519/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6520/// C++ method declaration. We're (re-)introducing the given
6521/// function parameter into scope for use in parsing later parts of
6522/// the method declaration. For example, we could see an
6523/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006524void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006525 if (!ParamD)
6526 return;
Mike Stump11289f42009-09-09 15:08:12 +00006527
John McCall48871652010-08-21 09:40:31 +00006528 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006529
6530 // If this parameter has an unparsed default argument, clear it out
6531 // to make way for the parsed default argument.
6532 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006533 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006534
John McCall48871652010-08-21 09:40:31 +00006535 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006536 if (Param->getDeclName())
6537 IdResolver.AddDecl(Param);
6538}
6539
6540/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6541/// processing the delayed method declaration for Method. The method
6542/// declaration is now considered finished. There may be a separate
6543/// ActOnStartOfFunctionDef action later (not necessarily
6544/// immediately!) for this method, if it was also defined inside the
6545/// class body.
John McCall48871652010-08-21 09:40:31 +00006546void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006547 if (!MethodD)
6548 return;
Mike Stump11289f42009-09-09 15:08:12 +00006549
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006550 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006551
John McCall48871652010-08-21 09:40:31 +00006552 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006553
6554 // Now that we have our default arguments, check the constructor
6555 // again. It could produce additional diagnostics or affect whether
6556 // the class has implicitly-declared destructors, among other
6557 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006558 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6559 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006560
6561 // Check the default arguments, which we may have added.
6562 if (!Method->isInvalidDecl())
6563 CheckCXXDefaultArguments(Method);
6564}
6565
Douglas Gregor831c93f2008-11-05 20:51:48 +00006566/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006567/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006568/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006569/// emit diagnostics and set the invalid bit to true. In any case, the type
6570/// will be updated to reflect a well-formed type for the constructor and
6571/// returned.
6572QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006573 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006574 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006575
6576 // C++ [class.ctor]p3:
6577 // A constructor shall not be virtual (10.3) or static (9.4). A
6578 // constructor can be invoked for a const, volatile or const
6579 // volatile object. A constructor shall not be declared const,
6580 // volatile, or const volatile (9.3.2).
6581 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006582 if (!D.isInvalidType())
6583 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6584 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6585 << SourceRange(D.getIdentifierLoc());
6586 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006587 }
John McCall8e7d6562010-08-26 03:08:43 +00006588 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006589 if (!D.isInvalidType())
6590 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6591 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6592 << SourceRange(D.getIdentifierLoc());
6593 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006594 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006595 }
Mike Stump11289f42009-09-09 15:08:12 +00006596
David Majnemer03f705f2014-07-08 18:18:04 +00006597 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6598 diagnoseIgnoredQualifiers(
6599 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6600 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6601 D.getDeclSpec().getRestrictSpecLoc(),
6602 D.getDeclSpec().getAtomicSpecLoc());
6603 D.setInvalidType();
6604 }
6605
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006606 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006607 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006608 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006609 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6610 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006611 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006612 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6613 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006614 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6616 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006617 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Douglas Gregordb9d6642011-01-26 05:01:58 +00006620 // C++0x [class.ctor]p4:
6621 // A constructor shall not be declared with a ref-qualifier.
6622 if (FTI.hasRefQualifier()) {
6623 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6624 << FTI.RefQualifierIsLValueRef
6625 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6626 D.setInvalidType();
6627 }
6628
Douglas Gregor831c93f2008-11-05 20:51:48 +00006629 // Rebuild the function type "R" without any type qualifiers (in
6630 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006631 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006632 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006633 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006634 return R;
6635
6636 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6637 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006638 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006639
6640 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006641}
6642
Douglas Gregor4d87df52008-12-16 21:30:33 +00006643/// CheckConstructor - Checks a fully-formed constructor for
6644/// well-formedness, issuing any diagnostics required. Returns true if
6645/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006646void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006647 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006648 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6649 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006650 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006651
6652 // C++ [class.copy]p3:
6653 // A declaration of a constructor for a class X is ill-formed if
6654 // its first parameter is of type (optionally cv-qualified) X and
6655 // either there are no other parameters or else all other
6656 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006657 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006658 ((Constructor->getNumParams() == 1) ||
6659 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006660 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6661 Constructor->getTemplateSpecializationKind()
6662 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006663 QualType ParamType = Constructor->getParamDecl(0)->getType();
6664 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6665 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006666 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006667 const char *ConstRef
6668 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6669 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006670 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006671 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006672
6673 // FIXME: Rather that making the constructor invalid, we should endeavor
6674 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006675 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006676 }
6677 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006678}
6679
John McCalldeb646e2010-08-04 01:04:25 +00006680/// CheckDestructor - Checks a fully-formed destructor definition for
6681/// well-formedness, issuing any diagnostics required. Returns true
6682/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006683bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006684 CXXRecordDecl *RD = Destructor->getParent();
6685
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006686 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006687 SourceLocation Loc;
6688
6689 if (!Destructor->isImplicit())
6690 Loc = Destructor->getLocation();
6691 else
6692 Loc = RD->getLocation();
6693
6694 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006695 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006696 DeclarationName Name =
6697 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006698 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006699 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006700 // If there's no class-specific operator delete, look up the global
6701 // non-array delete.
6702 if (!OperatorDelete)
6703 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006704
Eli Friedmanfa0df832012-02-02 03:46:19 +00006705 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006706
6707 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006708 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006709
6710 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006711}
6712
Douglas Gregor831c93f2008-11-05 20:51:48 +00006713/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6714/// the well-formednes of the destructor declarator @p D with type @p
6715/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006716/// emit diagnostics and set the declarator to invalid. Even if this happens,
6717/// will be updated to reflect a well-formed type for the destructor and
6718/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006719QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006720 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006721 // C++ [class.dtor]p1:
6722 // [...] A typedef-name that names a class is a class-name
6723 // (7.1.3); however, a typedef-name that names a class shall not
6724 // be used as the identifier in the declarator for a destructor
6725 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006726 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006727 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006728 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006729 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006730 else if (const TemplateSpecializationType *TST =
6731 DeclaratorType->getAs<TemplateSpecializationType>())
6732 if (TST->isTypeAlias())
6733 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6734 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006735
6736 // C++ [class.dtor]p2:
6737 // A destructor is used to destroy objects of its class type. A
6738 // destructor takes no parameters, and no return type can be
6739 // specified for it (not even void). The address of a destructor
6740 // shall not be taken. A destructor shall not be static. A
6741 // destructor can be invoked for a const, volatile or const
6742 // volatile object. A destructor shall not be declared const,
6743 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006744 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006745 if (!D.isInvalidType())
6746 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6747 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006748 << SourceRange(D.getIdentifierLoc())
6749 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6750
John McCall8e7d6562010-08-26 03:08:43 +00006751 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006752 }
David Majnemer03f705f2014-07-08 18:18:04 +00006753 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006754 // Destructors don't have return types, but the parser will
6755 // happily parse something like:
6756 //
6757 // class X {
6758 // float ~X();
6759 // };
6760 //
6761 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006762 if (D.getDeclSpec().hasTypeSpecifier())
6763 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6764 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6765 << SourceRange(D.getIdentifierLoc());
6766 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6767 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6768 SourceLocation(),
6769 D.getDeclSpec().getConstSpecLoc(),
6770 D.getDeclSpec().getVolatileSpecLoc(),
6771 D.getDeclSpec().getRestrictSpecLoc(),
6772 D.getDeclSpec().getAtomicSpecLoc());
6773 D.setInvalidType();
6774 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006775 }
Mike Stump11289f42009-09-09 15:08:12 +00006776
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006777 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006778 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006779 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006780 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6781 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006782 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6784 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006785 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006786 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6787 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006788 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006789 }
6790
Douglas Gregordb9d6642011-01-26 05:01:58 +00006791 // C++0x [class.dtor]p2:
6792 // A destructor shall not be declared with a ref-qualifier.
6793 if (FTI.hasRefQualifier()) {
6794 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6795 << FTI.RefQualifierIsLValueRef
6796 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6797 D.setInvalidType();
6798 }
6799
Douglas Gregor831c93f2008-11-05 20:51:48 +00006800 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006801 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006802 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6803
6804 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006805 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006806 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006807 }
6808
Mike Stump11289f42009-09-09 15:08:12 +00006809 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006810 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006811 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006812 D.setInvalidType();
6813 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006814
6815 // Rebuild the function type "R" without any type qualifiers or
6816 // parameters (in case any of the errors above fired) and with
6817 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006818 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006819 if (!D.isInvalidType())
6820 return R;
6821
Douglas Gregor95755162010-07-01 05:10:53 +00006822 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006823 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6824 EPI.Variadic = false;
6825 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006826 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006827 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006828}
6829
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006830/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6831/// well-formednes of the conversion function declarator @p D with
6832/// type @p R. If there are any errors in the declarator, this routine
6833/// will emit diagnostics and return true. Otherwise, it will return
6834/// false. Either way, the type @p R will be updated to reflect a
6835/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006836void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006837 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006838 // C++ [class.conv.fct]p1:
6839 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006840 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006841 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006842 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006843 if (!D.isInvalidType())
6844 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006845 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6846 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006847 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006848 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006849 }
John McCall212fa2e2010-04-13 00:04:31 +00006850
6851 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6852
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006853 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006854 // Conversion functions don't have return types, but the parser will
6855 // happily parse something like:
6856 //
6857 // class X {
6858 // float operator bool();
6859 // };
6860 //
6861 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006862 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6863 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6864 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006865 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006866 }
6867
John McCall212fa2e2010-04-13 00:04:31 +00006868 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6869
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006870 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006871 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006872 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6873
6874 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006875 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006876 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006877 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006878 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006879 D.setInvalidType();
6880 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006881
John McCall212fa2e2010-04-13 00:04:31 +00006882 // Diagnose "&operator bool()" and other such nonsense. This
6883 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006884 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006885 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006886 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006887 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006888 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006889 }
6890
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006891 // C++ [class.conv.fct]p4:
6892 // The conversion-type-id shall not represent a function type nor
6893 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006894 if (ConvType->isArrayType()) {
6895 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6896 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006897 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006898 } else if (ConvType->isFunctionType()) {
6899 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6900 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006901 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006902 }
6903
6904 // Rebuild the function type "R" without any parameters (in case any
6905 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006906 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006907 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006908 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006909
Douglas Gregor5fb53972009-01-14 15:45:31 +00006910 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006911 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006912 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006913 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006914 diag::warn_cxx98_compat_explicit_conversion_functions :
6915 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006916 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006917}
6918
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006919/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6920/// the declaration of the given C++ conversion function. This routine
6921/// is responsible for recording the conversion function in the C++
6922/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006923Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006924 assert(Conversion && "Expected to receive a conversion function declaration");
6925
Douglas Gregor4287b372008-12-12 08:25:50 +00006926 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006927
6928 // Make sure we aren't redeclaring the conversion function.
6929 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006930
6931 // C++ [class.conv.fct]p1:
6932 // [...] A conversion function is never used to convert a
6933 // (possibly cv-qualified) object to the (possibly cv-qualified)
6934 // same object type (or a reference to it), to a (possibly
6935 // cv-qualified) base class of that type (or a reference to it),
6936 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006937 // FIXME: Suppress this warning if the conversion function ends up being a
6938 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006939 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006940 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006941 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006942 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006943 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6944 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006945 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006946 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006947 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6948 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006949 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006950 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006951 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006952 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006953 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006954 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006955 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006956 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006957 }
6958
Douglas Gregor457104e2010-09-29 04:25:11 +00006959 if (FunctionTemplateDecl *ConversionTemplate
6960 = Conversion->getDescribedFunctionTemplate())
6961 return ConversionTemplate;
6962
John McCall48871652010-08-21 09:40:31 +00006963 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006964}
6965
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006966//===----------------------------------------------------------------------===//
6967// Namespace Handling
6968//===----------------------------------------------------------------------===//
6969
Richard Smith45bb8852012-10-04 22:13:39 +00006970/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6971/// reopened.
6972static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6973 SourceLocation Loc,
6974 IdentifierInfo *II, bool *IsInline,
6975 NamespaceDecl *PrevNS) {
6976 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006977
Richard Smithf501cc32012-10-05 01:46:25 +00006978 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6979 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6980 // inline namespaces, with the intention of bringing names into namespace std.
6981 //
6982 // We support this just well enough to get that case working; this is not
6983 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006984 if (*IsInline && II && II->getName().startswith("__atomic") &&
6985 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006986 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006987 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6988 NS = NS->getPreviousDecl())
6989 NS->setInline(*IsInline);
6990 // Patch up the lookup table for the containing namespace. This isn't really
6991 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006992 for (auto *I : PrevNS->decls())
6993 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006994 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6995 return;
6996 }
6997
6998 if (PrevNS->isInline())
6999 // The user probably just forgot the 'inline', so suggest that it
7000 // be added back.
7001 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7002 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7003 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007004 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007005
7006 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7007 *IsInline = PrevNS->isInline();
7008}
John McCallb1be5232010-08-26 09:15:37 +00007009
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007010/// ActOnStartNamespaceDef - This is called at the start of a namespace
7011/// definition.
John McCall48871652010-08-21 09:40:31 +00007012Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007013 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007014 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007015 SourceLocation IdentLoc,
7016 IdentifierInfo *II,
7017 SourceLocation LBrace,
7018 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007019 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7020 // For anonymous namespace, take the location of the left brace.
7021 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007022 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007023 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007024 bool IsStd = false;
7025 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007026 Scope *DeclRegionScope = NamespcScope->getParent();
7027
Craig Topperc3ec1492014-05-26 06:22:03 +00007028 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007029 if (II) {
7030 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007031 // The identifier in an original-namespace-definition shall not
7032 // have been previously defined in the declarative region in
7033 // which the original-namespace-definition appears. The
7034 // identifier in an original-namespace-definition is the name of
7035 // the namespace. Subsequently in that declarative region, it is
7036 // treated as an original-namespace-name.
7037 //
7038 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007039 // look through using directives, just look for any ordinary names.
7040
7041 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007042 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7043 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007044 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007045 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7046 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7047 ++I) {
7048 if ((*I)->getIdentifierNamespace() & IDNS) {
7049 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007050 break;
7051 }
7052 }
7053
Douglas Gregore57e7522012-01-07 09:11:48 +00007054 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7055
7056 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007057 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007058 if (IsInline != PrevNS->isInline())
7059 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7060 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007061 } else if (PrevDecl) {
7062 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007063 Diag(Loc, diag::err_redefinition_different_kind)
7064 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007065 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007066 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007067 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007068 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007069 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007070 // This is the first "real" definition of the namespace "std", so update
7071 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007072 PrevNS = getStdNamespace();
7073 IsStd = true;
7074 AddToKnown = !IsInline;
7075 } else {
7076 // We've seen this namespace for the first time.
7077 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007078 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007079 } else {
John McCall4fa53422009-10-01 00:25:31 +00007080 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007081
7082 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007083 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007084 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007085 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007086 } else {
7087 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007088 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007089 }
7090
Richard Smith45bb8852012-10-04 22:13:39 +00007091 if (PrevNS && IsInline != PrevNS->isInline())
7092 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7093 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007094 }
7095
7096 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7097 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007098 if (IsInvalid)
7099 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007100
7101 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007102
Douglas Gregore57e7522012-01-07 09:11:48 +00007103 // FIXME: Should we be merging attributes?
7104 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007105 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007106
7107 if (IsStd)
7108 StdNamespace = Namespc;
7109 if (AddToKnown)
7110 KnownNamespaces[Namespc] = false;
7111
7112 if (II) {
7113 PushOnScopeChains(Namespc, DeclRegionScope);
7114 } else {
7115 // Link the anonymous namespace into its parent.
7116 DeclContext *Parent = CurContext->getRedeclContext();
7117 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7118 TU->setAnonymousNamespace(Namespc);
7119 } else {
7120 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007121 }
John McCall4fa53422009-10-01 00:25:31 +00007122
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007123 CurContext->addDecl(Namespc);
7124
John McCall4fa53422009-10-01 00:25:31 +00007125 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7126 // behaves as if it were replaced by
7127 // namespace unique { /* empty body */ }
7128 // using namespace unique;
7129 // namespace unique { namespace-body }
7130 // where all occurrences of 'unique' in a translation unit are
7131 // replaced by the same identifier and this identifier differs
7132 // from all other identifiers in the entire program.
7133
7134 // We just create the namespace with an empty name and then add an
7135 // implicit using declaration, just like the standard suggests.
7136 //
7137 // CodeGen enforces the "universally unique" aspect by giving all
7138 // declarations semantically contained within an anonymous
7139 // namespace internal linkage.
7140
Douglas Gregore57e7522012-01-07 09:11:48 +00007141 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007142 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007143 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007144 /* 'using' */ LBrace,
7145 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007146 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007147 /* identifier */ SourceLocation(),
7148 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007149 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007150 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007151 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007152 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007153 }
7154
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007155 ActOnDocumentableDecl(Namespc);
7156
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007157 // Although we could have an invalid decl (i.e. the namespace name is a
7158 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007159 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7160 // for the namespace has the declarations that showed up in that particular
7161 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007162 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007163 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007164}
7165
Sebastian Redla6602e92009-11-23 15:34:23 +00007166/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7167/// is a namespace alias, returns the namespace it points to.
7168static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7169 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7170 return AD->getNamespace();
7171 return dyn_cast_or_null<NamespaceDecl>(D);
7172}
7173
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007174/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7175/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007176void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007177 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7178 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007179 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007180 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007181 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007182 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007183}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007184
John McCall28a0cf72010-08-25 07:42:41 +00007185CXXRecordDecl *Sema::getStdBadAlloc() const {
7186 return cast_or_null<CXXRecordDecl>(
7187 StdBadAlloc.get(Context.getExternalSource()));
7188}
7189
7190NamespaceDecl *Sema::getStdNamespace() const {
7191 return cast_or_null<NamespaceDecl>(
7192 StdNamespace.get(Context.getExternalSource()));
7193}
7194
Douglas Gregorcdf87022010-06-29 17:53:46 +00007195/// \brief Retrieve the special "std" namespace, which may require us to
7196/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007197NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007198 if (!StdNamespace) {
7199 // The "std" namespace has not yet been defined, so build one implicitly.
7200 StdNamespace = NamespaceDecl::Create(Context,
7201 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007202 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007203 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007204 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007205 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007206 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007207 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007208
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007209 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007210}
7211
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007212bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007213 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007214 "Looking for std::initializer_list outside of C++.");
7215
7216 // We're looking for implicit instantiations of
7217 // template <typename E> class std::initializer_list.
7218
7219 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7220 return false;
7221
Craig Topperc3ec1492014-05-26 06:22:03 +00007222 ClassTemplateDecl *Template = nullptr;
7223 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007224
Sebastian Redl43144e72012-01-17 22:49:58 +00007225 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007226
Sebastian Redl43144e72012-01-17 22:49:58 +00007227 ClassTemplateSpecializationDecl *Specialization =
7228 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7229 if (!Specialization)
7230 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007231
Sebastian Redl43144e72012-01-17 22:49:58 +00007232 Template = Specialization->getSpecializedTemplate();
7233 Arguments = Specialization->getTemplateArgs().data();
7234 } else if (const TemplateSpecializationType *TST =
7235 Ty->getAs<TemplateSpecializationType>()) {
7236 Template = dyn_cast_or_null<ClassTemplateDecl>(
7237 TST->getTemplateName().getAsTemplateDecl());
7238 Arguments = TST->getArgs();
7239 }
7240 if (!Template)
7241 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007242
7243 if (!StdInitializerList) {
7244 // Haven't recognized std::initializer_list yet, maybe this is it.
7245 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7246 if (TemplateClass->getIdentifier() !=
7247 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007248 !getStdNamespace()->InEnclosingNamespaceSetOf(
7249 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007250 return false;
7251 // This is a template called std::initializer_list, but is it the right
7252 // template?
7253 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007254 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007255 return false;
7256 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7257 return false;
7258
7259 // It's the right template.
7260 StdInitializerList = Template;
7261 }
7262
7263 if (Template != StdInitializerList)
7264 return false;
7265
7266 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007267 if (Element)
7268 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007269 return true;
7270}
7271
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007272static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7273 NamespaceDecl *Std = S.getStdNamespace();
7274 if (!Std) {
7275 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007276 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007277 }
7278
7279 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7280 Loc, Sema::LookupOrdinaryName);
7281 if (!S.LookupQualifiedName(Result, Std)) {
7282 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007283 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007284 }
7285 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7286 if (!Template) {
7287 Result.suppressDiagnostics();
7288 // We found something weird. Complain about the first thing we found.
7289 NamedDecl *Found = *Result.begin();
7290 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007291 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007292 }
7293
7294 // We found some template called std::initializer_list. Now verify that it's
7295 // correct.
7296 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007297 if (Params->getMinRequiredArguments() != 1 ||
7298 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007299 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007300 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007301 }
7302
7303 return Template;
7304}
7305
7306QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7307 if (!StdInitializerList) {
7308 StdInitializerList = LookupStdInitializerList(*this, Loc);
7309 if (!StdInitializerList)
7310 return QualType();
7311 }
7312
7313 TemplateArgumentListInfo Args(Loc, Loc);
7314 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7315 Context.getTrivialTypeSourceInfo(Element,
7316 Loc)));
7317 return Context.getCanonicalType(
7318 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7319}
7320
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007321bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7322 // C++ [dcl.init.list]p2:
7323 // A constructor is an initializer-list constructor if its first parameter
7324 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7325 // std::initializer_list<E> for some type E, and either there are no other
7326 // parameters or else all other parameters have default arguments.
7327 if (Ctor->getNumParams() < 1 ||
7328 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7329 return false;
7330
7331 QualType ArgType = Ctor->getParamDecl(0)->getType();
7332 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7333 ArgType = RT->getPointeeType().getUnqualifiedType();
7334
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007336}
7337
Douglas Gregora172e082011-03-26 22:25:30 +00007338/// \brief Determine whether a using statement is in a context where it will be
7339/// apply in all contexts.
7340static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7341 switch (CurContext->getDeclKind()) {
7342 case Decl::TranslationUnit:
7343 return true;
7344 case Decl::LinkageSpec:
7345 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7346 default:
7347 return false;
7348 }
7349}
7350
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007351namespace {
7352
7353// Callback to only accept typo corrections that are namespaces.
7354class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007355public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007356 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007357 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007358 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007359 return false;
7360 }
7361};
7362
7363}
7364
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007365static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7366 CXXScopeSpec &SS,
7367 SourceLocation IdentLoc,
7368 IdentifierInfo *Ident) {
7369 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007370 if (TypoCorrection Corrected =
7371 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7372 llvm::make_unique<NamespaceValidatorCCC>(),
7373 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007374 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007375 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7376 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007377 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007378 S.diagnoseTypo(Corrected,
7379 S.PDiag(diag::err_using_directive_member_suggest)
7380 << Ident << DC << DroppedSpecifier << SS.getRange(),
7381 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007382 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007383 S.diagnoseTypo(Corrected,
7384 S.PDiag(diag::err_using_directive_suggest) << Ident,
7385 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007386 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007387 R.addDecl(Corrected.getCorrectionDecl());
7388 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007389 }
7390 return false;
7391}
7392
John McCall48871652010-08-21 09:40:31 +00007393Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007394 SourceLocation UsingLoc,
7395 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007396 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007397 SourceLocation IdentLoc,
7398 IdentifierInfo *NamespcName,
7399 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007400 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7401 assert(NamespcName && "Invalid NamespcName.");
7402 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007403
7404 // This can only happen along a recovery path.
7405 while (S->getFlags() & Scope::TemplateParamScope)
7406 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007407 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007408
Craig Topperc3ec1492014-05-26 06:22:03 +00007409 UsingDirectiveDecl *UDir = nullptr;
7410 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007411 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007412 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007413
Douglas Gregor34074322009-01-14 22:20:51 +00007414 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007415 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7416 LookupParsedName(R, S, &SS);
7417 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007418 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007419
Douglas Gregorcdf87022010-06-29 17:53:46 +00007420 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007421 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007422 // Allow "using namespace std;" or "using namespace ::std;" even if
7423 // "std" hasn't been defined yet, for GCC compatibility.
7424 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7425 NamespcName->isStr("std")) {
7426 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007427 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007428 R.resolveKind();
7429 }
7430 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007431 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007432 }
7433
John McCall9f3059a2009-10-09 21:13:30 +00007434 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007435 NamedDecl *Named = R.getFoundDecl();
7436 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7437 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007438
Nico Riecke50e59a2014-11-24 17:29:52 +00007439 // The use of a nested name specifier may trigger deprecation warnings.
7440 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007441
Douglas Gregor889ceb72009-02-03 19:21:40 +00007442 // C++ [namespace.udir]p1:
7443 // A using-directive specifies that the names in the nominated
7444 // namespace can be used in the scope in which the
7445 // using-directive appears after the using-directive. During
7446 // unqualified name lookup (3.4.1), the names appear as if they
7447 // were declared in the nearest enclosing namespace which
7448 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007449 // namespace. [Note: in this context, "contains" means "contains
7450 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007451
7452 // Find enclosing context containing both using-directive and
7453 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007454 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007455 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7456 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7457 CommonAncestor = CommonAncestor->getParent();
7458
Sebastian Redla6602e92009-11-23 15:34:23 +00007459 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007460 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007461 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007462
Douglas Gregora172e082011-03-26 22:25:30 +00007463 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007464 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007465 Diag(IdentLoc, diag::warn_using_directive_in_header);
7466 }
7467
Douglas Gregor889ceb72009-02-03 19:21:40 +00007468 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007469 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007470 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007471 }
7472
Richard Smith54ecd982013-02-20 19:22:51 +00007473 if (UDir)
7474 ProcessDeclAttributeList(S, UDir, AttrList);
7475
John McCall48871652010-08-21 09:40:31 +00007476 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007477}
7478
7479void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007480 // If the scope has an associated entity and the using directive is at
7481 // namespace or translation unit scope, add the UsingDirectiveDecl into
7482 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007483 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007484 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007485 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007486 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007487 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007488 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007489 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007490}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007491
Douglas Gregorfec52632009-06-20 00:51:54 +00007492
John McCall48871652010-08-21 09:40:31 +00007493Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007494 AccessSpecifier AS,
7495 bool HasUsingKeyword,
7496 SourceLocation UsingLoc,
7497 CXXScopeSpec &SS,
7498 UnqualifiedId &Name,
7499 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007500 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007501 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007502 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007503
Douglas Gregor220f4272009-11-04 16:30:06 +00007504 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007505 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007506 case UnqualifiedId::IK_Identifier:
7507 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007508 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007509 case UnqualifiedId::IK_ConversionFunctionId:
7510 break;
7511
7512 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007513 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007514 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007515 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007516 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007517 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007518 diag::err_using_decl_constructor)
7519 << SS.getRange();
7520
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007521 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007522
Craig Topperc3ec1492014-05-26 06:22:03 +00007523 return nullptr;
7524
Douglas Gregor220f4272009-11-04 16:30:06 +00007525 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007526 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007527 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007528 return nullptr;
7529
Douglas Gregor220f4272009-11-04 16:30:06 +00007530 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007531 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007532 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007533 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007534 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007535
7536 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7537 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007538 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007539 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007540
Richard Smithc2bc61b2013-03-18 21:12:30 +00007541 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007542 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007543 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007544 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7545 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007546 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007547 }
7548
Douglas Gregorc4356532010-12-16 00:46:58 +00007549 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7550 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007551 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007552
John McCall3f746822009-11-17 05:59:44 +00007553 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007554 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007555 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007556 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007557 if (UD)
7558 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007559
John McCall48871652010-08-21 09:40:31 +00007560 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007561}
7562
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007563/// \brief Determine whether a using declaration considers the given
7564/// declarations as "equivalent", e.g., if they are redeclarations of
7565/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007566static bool
7567IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7568 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007569 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007570
Richard Smithdda56e42011-04-15 14:24:37 +00007571 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007572 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007573 return Context.hasSameType(TD1->getUnderlyingType(),
7574 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007575
7576 return false;
7577}
7578
7579
John McCall84d87672009-12-10 09:41:52 +00007580/// Determines whether to create a using shadow decl for a particular
7581/// decl, given the set of decls existing prior to this using lookup.
7582bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007583 const LookupResult &Previous,
7584 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007585 // Diagnose finding a decl which is not from a base class of the
7586 // current class. We do this now because there are cases where this
7587 // function will silently decide not to build a shadow decl, which
7588 // will pre-empt further diagnostics.
7589 //
7590 // We don't need to do this in C++0x because we do the check once on
7591 // the qualifier.
7592 //
7593 // FIXME: diagnose the following if we care enough:
7594 // struct A { int foo; };
7595 // struct B : A { using A::foo; };
7596 // template <class T> struct C : A {};
7597 // template <class T> struct D : C<T> { using B::foo; } // <---
7598 // This is invalid (during instantiation) in C++03 because B::foo
7599 // resolves to the using decl in B, which is not a base class of D<T>.
7600 // We can't diagnose it immediately because C<T> is an unknown
7601 // specialization. The UsingShadowDecl in D<T> then points directly
7602 // to A::foo, which will look well-formed when we instantiate.
7603 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007604 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007605 DeclContext *OrigDC = Orig->getDeclContext();
7606
7607 // Handle enums and anonymous structs.
7608 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7609 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7610 while (OrigRec->isAnonymousStructOrUnion())
7611 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7612
7613 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7614 if (OrigDC == CurContext) {
7615 Diag(Using->getLocation(),
7616 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007617 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007618 Diag(Orig->getLocation(), diag::note_using_decl_target);
7619 return true;
7620 }
7621
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007622 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007623 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007624 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007625 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007626 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007627 Diag(Orig->getLocation(), diag::note_using_decl_target);
7628 return true;
7629 }
7630 }
7631
7632 if (Previous.empty()) return false;
7633
7634 NamedDecl *Target = Orig;
7635 if (isa<UsingShadowDecl>(Target))
7636 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7637
John McCalla17e83e2009-12-11 02:33:26 +00007638 // If the target happens to be one of the previous declarations, we
7639 // don't have a conflict.
7640 //
7641 // FIXME: but we might be increasing its access, in which case we
7642 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007643 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007644 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007645 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7646 I != E; ++I) {
7647 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007648 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7649 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7650 PrevShadow = Shadow;
7651 FoundEquivalentDecl = true;
7652 }
John McCalla17e83e2009-12-11 02:33:26 +00007653
7654 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7655 }
7656
Richard Smithfd8634a2013-10-23 02:17:46 +00007657 if (FoundEquivalentDecl)
7658 return false;
7659
Alp Tokera2794f92014-01-22 07:29:52 +00007660 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007661 NamedDecl *OldDecl = nullptr;
7662 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7663 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007664 case Ovl_Overload:
7665 return false;
7666
7667 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007668 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007669 break;
Richard Smith18819302014-02-06 01:31:33 +00007670
John McCall84d87672009-12-10 09:41:52 +00007671 // We found a decl with the exact signature.
7672 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007673 // If we're in a record, we want to hide the target, so we
7674 // return true (without a diagnostic) to tell the caller not to
7675 // build a shadow decl.
7676 if (CurContext->isRecord())
7677 return true;
7678
7679 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007680 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007681 break;
7682 }
7683
7684 Diag(Target->getLocation(), diag::note_using_decl_target);
7685 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7686 return true;
7687 }
7688
7689 // Target is not a function.
7690
John McCall84d87672009-12-10 09:41:52 +00007691 if (isa<TagDecl>(Target)) {
7692 // No conflict between a tag and a non-tag.
7693 if (!Tag) return false;
7694
John McCalle29c5cd2009-12-10 19:51:03 +00007695 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007696 Diag(Target->getLocation(), diag::note_using_decl_target);
7697 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7698 return true;
7699 }
7700
7701 // No conflict between a tag and a non-tag.
7702 if (!NonTag) return false;
7703
John McCalle29c5cd2009-12-10 19:51:03 +00007704 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007705 Diag(Target->getLocation(), diag::note_using_decl_target);
7706 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7707 return true;
7708}
7709
John McCall3f746822009-11-17 05:59:44 +00007710/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007711UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007712 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007713 NamedDecl *Orig,
7714 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007715
7716 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007717 NamedDecl *Target = Orig;
7718 if (isa<UsingShadowDecl>(Target)) {
7719 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7720 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007721 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007722
John McCall3f746822009-11-17 05:59:44 +00007723 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007724 = UsingShadowDecl::Create(Context, CurContext,
7725 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007726 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007727
Douglas Gregor457104e2010-09-29 04:25:11 +00007728 Shadow->setAccess(UD->getAccess());
7729 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7730 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007731
7732 Shadow->setPreviousDecl(PrevDecl);
7733
John McCall3f746822009-11-17 05:59:44 +00007734 if (S)
John McCall3969e302009-12-08 07:46:18 +00007735 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007736 else
John McCall3969e302009-12-08 07:46:18 +00007737 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007738
John McCall3969e302009-12-08 07:46:18 +00007739
John McCall84d87672009-12-10 09:41:52 +00007740 return Shadow;
7741}
John McCall3969e302009-12-08 07:46:18 +00007742
John McCall84d87672009-12-10 09:41:52 +00007743/// Hides a using shadow declaration. This is required by the current
7744/// using-decl implementation when a resolvable using declaration in a
7745/// class is followed by a declaration which would hide or override
7746/// one or more of the using decl's targets; for example:
7747///
7748/// struct Base { void foo(int); };
7749/// struct Derived : Base {
7750/// using Base::foo;
7751/// void foo(int);
7752/// };
7753///
7754/// The governing language is C++03 [namespace.udecl]p12:
7755///
7756/// When a using-declaration brings names from a base class into a
7757/// derived class scope, member functions in the derived class
7758/// override and/or hide member functions with the same name and
7759/// parameter types in a base class (rather than conflicting).
7760///
7761/// There are two ways to implement this:
7762/// (1) optimistically create shadow decls when they're not hidden
7763/// by existing declarations, or
7764/// (2) don't create any shadow decls (or at least don't make them
7765/// visible) until we've fully parsed/instantiated the class.
7766/// The problem with (1) is that we might have to retroactively remove
7767/// a shadow decl, which requires several O(n) operations because the
7768/// decl structures are (very reasonably) not designed for removal.
7769/// (2) avoids this but is very fiddly and phase-dependent.
7770void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007771 if (Shadow->getDeclName().getNameKind() ==
7772 DeclarationName::CXXConversionFunctionName)
7773 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7774
John McCall84d87672009-12-10 09:41:52 +00007775 // Remove it from the DeclContext...
7776 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007777
John McCall84d87672009-12-10 09:41:52 +00007778 // ...and the scope, if applicable...
7779 if (S) {
John McCall48871652010-08-21 09:40:31 +00007780 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007781 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007782 }
7783
John McCall84d87672009-12-10 09:41:52 +00007784 // ...and the using decl.
7785 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7786
7787 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007788 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007789}
7790
Richard Smith09d5b3a2014-05-01 00:35:04 +00007791/// Find the base specifier for a base class with the given type.
7792static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7793 QualType DesiredBase,
7794 bool &AnyDependentBases) {
7795 // Check whether the named type is a direct base class.
7796 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7797 for (auto &Base : Derived->bases()) {
7798 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7799 if (CanonicalDesiredBase == BaseType)
7800 return &Base;
7801 if (BaseType->isDependentType())
7802 AnyDependentBases = true;
7803 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007804 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007805}
7806
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007807namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007808class UsingValidatorCCC : public CorrectionCandidateCallback {
7809public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007810 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007811 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007812 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007813 IsInstantiation(IsInstantiation), OldNNS(NNS),
7814 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007815
Craig Toppera798a9d2014-03-02 09:32:10 +00007816 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007817 NamedDecl *ND = Candidate.getCorrectionDecl();
7818
7819 // Keywords are not valid here.
7820 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007821 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007822
7823 // Completely unqualified names are invalid for a 'using' declaration.
7824 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7825 return false;
7826
Richard Smith09d5b3a2014-05-01 00:35:04 +00007827 if (RequireMemberOf) {
7828 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7829 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7830 // No-one ever wants a using-declaration to name an injected-class-name
7831 // of a base class, unless they're declaring an inheriting constructor.
7832 ASTContext &Ctx = ND->getASTContext();
7833 if (!Ctx.getLangOpts().CPlusPlus11)
7834 return false;
7835 QualType FoundType = Ctx.getRecordType(FoundRecord);
7836
7837 // Check that the injected-class-name is named as a member of its own
7838 // type; we don't want to suggest 'using Derived::Base;', since that
7839 // means something else.
7840 NestedNameSpecifier *Specifier =
7841 Candidate.WillReplaceSpecifier()
7842 ? Candidate.getCorrectionSpecifier()
7843 : OldNNS;
7844 if (!Specifier->getAsType() ||
7845 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7846 return false;
7847
7848 // Check that this inheriting constructor declaration actually names a
7849 // direct base class of the current class.
7850 bool AnyDependentBases = false;
7851 if (!findDirectBaseWithType(RequireMemberOf,
7852 Ctx.getRecordType(FoundRecord),
7853 AnyDependentBases) &&
7854 !AnyDependentBases)
7855 return false;
7856 } else {
7857 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7858 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7859 return false;
7860
7861 // FIXME: Check that the base class member is accessible?
7862 }
7863 }
7864
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007865 if (isa<TypeDecl>(ND))
7866 return HasTypenameKeyword || !IsInstantiation;
7867
7868 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007869 }
7870
7871private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007872 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007873 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007874 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007875 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007876};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007877} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007878
John McCalle61f2ba2009-11-18 02:36:19 +00007879/// Builds a using declaration.
7880///
7881/// \param IsInstantiation - Whether this call arises from an
7882/// instantiation of an unresolved using declaration. We treat
7883/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007884NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7885 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007886 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007887 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007888 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007889 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007890 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007891 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007892 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007893 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007894 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007895
Anders Carlssonf038fc22009-08-28 05:49:21 +00007896 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007897
Anders Carlsson59140b32009-08-28 03:16:11 +00007898 if (SS.isEmpty()) {
7899 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007900 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007901 }
Mike Stump11289f42009-09-09 15:08:12 +00007902
John McCall84d87672009-12-10 09:41:52 +00007903 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007904 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007905 ForRedeclaration);
7906 Previous.setHideTags(false);
7907 if (S) {
7908 LookupName(Previous, S);
7909
7910 // It is really dumb that we have to do this.
7911 LookupResult::Filter F = Previous.makeFilter();
7912 while (F.hasNext()) {
7913 NamedDecl *D = F.next();
7914 if (!isDeclInScope(D, CurContext, S))
7915 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007916 // If we found a local extern declaration that's not ordinarily visible,
7917 // and this declaration is being added to a non-block scope, ignore it.
7918 // We're only checking for scope conflicts here, not also for violations
7919 // of the linkage rules.
7920 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7921 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7922 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007923 }
7924 F.done();
7925 } else {
7926 assert(IsInstantiation && "no scope in non-instantiation");
7927 assert(CurContext->isRecord() && "scope not record in instantiation");
7928 LookupQualifiedName(Previous, CurContext);
7929 }
7930
John McCall84d87672009-12-10 09:41:52 +00007931 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007932 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7933 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007934 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007935
7936 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007937 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007938 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007939
John McCall84c16cf2009-11-12 03:15:40 +00007940 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007941 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007942 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007943 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007944 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007945 // FIXME: not all declaration name kinds are legal here
7946 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7947 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007948 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007949 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007950 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007951 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7952 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007953 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007954 D->setAccess(AS);
7955 CurContext->addDecl(D);
7956 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007957 }
John McCallb96ec562009-12-04 22:46:56 +00007958
Richard Smith09d5b3a2014-05-01 00:35:04 +00007959 auto Build = [&](bool Invalid) {
7960 UsingDecl *UD =
7961 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7962 HasTypenameKeyword);
7963 UD->setAccess(AS);
7964 CurContext->addDecl(UD);
7965 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007966 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007967 };
7968 auto BuildInvalid = [&]{ return Build(true); };
7969 auto BuildValid = [&]{ return Build(false); };
7970
7971 if (RequireCompleteDeclContext(SS, LookupContext))
7972 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007973
Richard Smith23d55872012-04-02 01:30:27 +00007974 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007975 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007976 UsingDecl *UD = BuildValid();
7977 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007978 return UD;
7979 }
7980
7981 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007982
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007983 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007984
John McCall3969e302009-12-08 07:46:18 +00007985 // Unlike most lookups, we don't always want to hide tag
7986 // declarations: tag names are visible through the using declaration
7987 // even if hidden by ordinary names, *except* in a dependent context
7988 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007989 if (!IsInstantiation)
7990 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007991
John McCall5dadb652012-04-07 03:04:20 +00007992 // For the purposes of this lookup, we have a base object type
7993 // equal to that of the current context.
7994 if (CurContext->isRecord()) {
7995 R.setBaseObjectType(
7996 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7997 }
7998
John McCall27b18f82009-11-17 02:14:36 +00007999 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008000
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008001 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00008002 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008003 if (TypoCorrection Corrected = CorrectTypo(
8004 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8005 llvm::make_unique<UsingValidatorCCC>(
8006 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8007 dyn_cast<CXXRecordDecl>(CurContext)),
8008 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008009 // We reject any correction for which ND would be NULL.
8010 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008011
Richard Smithf9b15102013-08-17 00:46:16 +00008012 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008013 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008014 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8015 << NameInfo.getName() << LookupContext << 0
8016 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008017
8018 // If we corrected to an inheriting constructor, handle it as one.
8019 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8020 if (RD && RD->isInjectedClassName()) {
8021 // Fix up the information we'll use to build the using declaration.
8022 if (Corrected.WillReplaceSpecifier()) {
8023 NestedNameSpecifierLocBuilder Builder;
8024 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8025 QualifierLoc.getSourceRange());
8026 QualifierLoc = Builder.getWithLocInContext(Context);
8027 }
8028
8029 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8030 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008031 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008032
8033 // Build it and process it as an inheriting constructor.
8034 UsingDecl *UD = BuildValid();
8035 CheckInheritingConstructorUsingDecl(UD);
8036 return UD;
8037 }
8038
8039 // FIXME: Pick up all the declarations if we found an overloaded function.
8040 R.setLookupName(Corrected.getCorrection());
8041 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008042 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008043 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008044 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008045 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008046 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008047 }
8048
Richard Smith09d5b3a2014-05-01 00:35:04 +00008049 if (R.isAmbiguous())
8050 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008051
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008052 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008053 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008054 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008055 Diag(IdentLoc, diag::err_using_typename_non_type);
8056 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8057 Diag((*I)->getUnderlyingDecl()->getLocation(),
8058 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008059 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008060 }
8061 } else {
8062 // If we asked for a non-typename and we got a type, error out,
8063 // but only if this is an instantiation of an unresolved using
8064 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008065 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008066 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8067 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008068 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008069 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008070 }
8071
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008072 // C++0x N2914 [namespace.udecl]p6:
8073 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008074 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008075 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8076 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008077 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008078 }
Mike Stump11289f42009-09-09 15:08:12 +00008079
Richard Smith09d5b3a2014-05-01 00:35:04 +00008080 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008081 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008082 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008083 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8084 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008085 }
John McCall3f746822009-11-17 05:59:44 +00008086
8087 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008088}
8089
Sebastian Redl08905022011-02-05 19:23:19 +00008090/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008091bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008092 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008093
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008094 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008095 assert(SourceType &&
8096 "Using decl naming constructor doesn't have type in scope spec.");
8097 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8098
8099 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008100 bool AnyDependentBases = false;
8101 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8102 AnyDependentBases);
8103 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008104 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008105 diag::err_using_decl_constructor_not_in_direct_base)
8106 << UD->getNameInfo().getSourceRange()
8107 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008108 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008109 return true;
8110 }
8111
Richard Smith09d5b3a2014-05-01 00:35:04 +00008112 if (Base)
8113 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008114
8115 return false;
8116}
8117
John McCall84d87672009-12-10 09:41:52 +00008118/// Checks that the given using declaration is not an invalid
8119/// redeclaration. Note that this is checking only for the using decl
8120/// itself, not for any ill-formedness among the UsingShadowDecls.
8121bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008122 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008123 const CXXScopeSpec &SS,
8124 SourceLocation NameLoc,
8125 const LookupResult &Prev) {
8126 // C++03 [namespace.udecl]p8:
8127 // C++0x [namespace.udecl]p10:
8128 // A using-declaration is a declaration and can therefore be used
8129 // repeatedly where (and only where) multiple declarations are
8130 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008131 //
John McCall032092f2010-11-29 18:01:58 +00008132 // That's in non-member contexts.
8133 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008134 return false;
8135
Aaron Ballman4a979672014-01-03 13:56:08 +00008136 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008137
8138 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8139 NamedDecl *D = *I;
8140
8141 bool DTypename;
8142 NestedNameSpecifier *DQual;
8143 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008144 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008145 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008146 } else if (UnresolvedUsingValueDecl *UD
8147 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8148 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008149 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008150 } else if (UnresolvedUsingTypenameDecl *UD
8151 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8152 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008153 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008154 } else continue;
8155
8156 // using decls differ if one says 'typename' and the other doesn't.
8157 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008158 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008159
8160 // using decls differ if they name different scopes (but note that
8161 // template instantiation can cause this check to trigger when it
8162 // didn't before instantiation).
8163 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8164 Context.getCanonicalNestedNameSpecifier(DQual))
8165 continue;
8166
8167 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008168 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008169 return true;
8170 }
8171
8172 return false;
8173}
8174
John McCall3969e302009-12-08 07:46:18 +00008175
John McCallb96ec562009-12-04 22:46:56 +00008176/// Checks that the given nested-name qualifier used in a using decl
8177/// in the current context is appropriately related to the current
8178/// scope. If an error is found, diagnoses it and returns true.
8179bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8180 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008181 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008182 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008183 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008184
John McCall3969e302009-12-08 07:46:18 +00008185 if (!CurContext->isRecord()) {
8186 // C++03 [namespace.udecl]p3:
8187 // C++0x [namespace.udecl]p8:
8188 // A using-declaration for a class member shall be a member-declaration.
8189
8190 // If we weren't able to compute a valid scope, it must be a
8191 // dependent class scope.
8192 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00008193 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8194 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008195 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008196
John McCall3969e302009-12-08 07:46:18 +00008197 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8198 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008199
8200 // If we have a complete, non-dependent source type, try to suggest a
8201 // way to get the same effect.
8202 if (!RD)
8203 return true;
8204
8205 // Find what this using-declaration was referring to.
8206 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8207 R.setHideTags(false);
8208 R.suppressDiagnostics();
8209 LookupQualifiedName(R, RD);
8210
8211 if (R.getAsSingle<TypeDecl>()) {
8212 if (getLangOpts().CPlusPlus11) {
8213 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8214 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8215 << 0 // alias declaration
8216 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8217 NameInfo.getName().getAsString() +
8218 " = ");
8219 } else {
8220 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8221 SourceLocation InsertLoc =
8222 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8223 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8224 << 1 // typedef declaration
8225 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8226 << FixItHint::CreateInsertion(
8227 InsertLoc, " " + NameInfo.getName().getAsString());
8228 }
8229 } else if (R.getAsSingle<VarDecl>()) {
8230 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8231 // repeating the type of the static data member here.
8232 FixItHint FixIt;
8233 if (getLangOpts().CPlusPlus11) {
8234 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8235 FixIt = FixItHint::CreateReplacement(
8236 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8237 }
8238
8239 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8240 << 2 // reference declaration
8241 << FixIt;
8242 }
John McCall3969e302009-12-08 07:46:18 +00008243 return true;
8244 }
8245
8246 // Otherwise, everything is known to be fine.
8247 return false;
8248 }
8249
8250 // The current scope is a record.
8251
8252 // If the named context is dependent, we can't decide much.
8253 if (!NamedContext) {
8254 // FIXME: in C++0x, we can diagnose if we can prove that the
8255 // nested-name-specifier does not refer to a base class, which is
8256 // still possible in some cases.
8257
8258 // Otherwise we have to conservatively report that things might be
8259 // okay.
8260 return false;
8261 }
8262
8263 if (!NamedContext->isRecord()) {
8264 // Ideally this would point at the last name in the specifier,
8265 // but we don't have that level of source info.
8266 Diag(SS.getRange().getBegin(),
8267 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008268 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008269 return true;
8270 }
8271
Douglas Gregor7c842292010-12-21 07:41:49 +00008272 if (!NamedContext->isDependentContext() &&
8273 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8274 return true;
8275
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008276 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008277 // C++0x [namespace.udecl]p3:
8278 // In a using-declaration used as a member-declaration, the
8279 // nested-name-specifier shall name a base class of the class
8280 // being defined.
8281
8282 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8283 cast<CXXRecordDecl>(NamedContext))) {
8284 if (CurContext == NamedContext) {
8285 Diag(NameLoc,
8286 diag::err_using_decl_nested_name_specifier_is_current_class)
8287 << SS.getRange();
8288 return true;
8289 }
8290
8291 Diag(SS.getRange().getBegin(),
8292 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008293 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008294 << cast<CXXRecordDecl>(CurContext)
8295 << SS.getRange();
8296 return true;
8297 }
8298
8299 return false;
8300 }
8301
8302 // C++03 [namespace.udecl]p4:
8303 // A using-declaration used as a member-declaration shall refer
8304 // to a member of a base class of the class being defined [etc.].
8305
8306 // Salient point: SS doesn't have to name a base class as long as
8307 // lookup only finds members from base classes. Therefore we can
8308 // diagnose here only if we can prove that that can't happen,
8309 // i.e. if the class hierarchies provably don't intersect.
8310
8311 // TODO: it would be nice if "definitely valid" results were cached
8312 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8313 // need to be repeated.
8314
8315 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008316 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008317
8318 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8319 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8320 Data->Bases.insert(Base);
8321 return true;
8322 }
8323
8324 bool hasDependentBases(const CXXRecordDecl *Class) {
8325 return !Class->forallBases(collect, this);
8326 }
8327
8328 /// Returns true if the base is dependent or is one of the
8329 /// accumulated base classes.
8330 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8331 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8332 return !Data->Bases.count(Base);
8333 }
8334
8335 bool mightShareBases(const CXXRecordDecl *Class) {
8336 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8337 }
8338 };
8339
8340 UserData Data;
8341
8342 // Returns false if we find a dependent base.
8343 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8344 return false;
8345
8346 // Returns false if the class has a dependent base or if it or one
8347 // of its bases is present in the base set of the current context.
8348 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8349 return false;
8350
8351 Diag(SS.getRange().getBegin(),
8352 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008353 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008354 << cast<CXXRecordDecl>(CurContext)
8355 << SS.getRange();
8356
8357 return true;
John McCallb96ec562009-12-04 22:46:56 +00008358}
8359
Richard Smithdda56e42011-04-15 14:24:37 +00008360Decl *Sema::ActOnAliasDeclaration(Scope *S,
8361 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008362 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008363 SourceLocation UsingLoc,
8364 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008365 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008366 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008367 // Skip up to the relevant declaration scope.
8368 while (S->getFlags() & Scope::TemplateParamScope)
8369 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008370 assert((S->getFlags() & Scope::DeclScope) &&
8371 "got alias-declaration outside of declaration scope");
8372
8373 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008374 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008375
8376 bool Invalid = false;
8377 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008378 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008379 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008380
8381 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008382 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008383
8384 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008385 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008386 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008387 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8388 TInfo->getTypeLoc().getBeginLoc());
8389 }
Richard Smithdda56e42011-04-15 14:24:37 +00008390
8391 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8392 LookupName(Previous, S);
8393
8394 // Warn about shadowing the name of a template parameter.
8395 if (Previous.isSingleResult() &&
8396 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008397 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008398 Previous.clear();
8399 }
8400
8401 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8402 "name in alias declaration must be an identifier");
8403 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8404 Name.StartLocation,
8405 Name.Identifier, TInfo);
8406
8407 NewTD->setAccess(AS);
8408
8409 if (Invalid)
8410 NewTD->setInvalidDecl();
8411
Richard Smith54ecd982013-02-20 19:22:51 +00008412 ProcessDeclAttributeList(S, NewTD, AttrList);
8413
Richard Smith3f1b5d02011-05-05 21:57:07 +00008414 CheckTypedefForVariablyModifiedType(S, NewTD);
8415 Invalid |= NewTD->isInvalidDecl();
8416
Richard Smithdda56e42011-04-15 14:24:37 +00008417 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008418
8419 NamedDecl *NewND;
8420 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008421 TypeAliasTemplateDecl *OldDecl = nullptr;
8422 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008423
8424 if (TemplateParamLists.size() != 1) {
8425 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008426 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8427 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008428 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008429 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008430
8431 // Only consider previous declarations in the same scope.
8432 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8433 /*ExplicitInstantiationOrSpecialization*/false);
8434 if (!Previous.empty()) {
8435 Redeclaration = true;
8436
8437 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8438 if (!OldDecl && !Invalid) {
8439 Diag(UsingLoc, diag::err_redefinition_different_kind)
8440 << Name.Identifier;
8441
8442 NamedDecl *OldD = Previous.getRepresentativeDecl();
8443 if (OldD->getLocation().isValid())
8444 Diag(OldD->getLocation(), diag::note_previous_definition);
8445
8446 Invalid = true;
8447 }
8448
8449 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8450 if (TemplateParameterListsAreEqual(TemplateParams,
8451 OldDecl->getTemplateParameters(),
8452 /*Complain=*/true,
8453 TPL_TemplateMatch))
8454 OldTemplateParams = OldDecl->getTemplateParameters();
8455 else
8456 Invalid = true;
8457
8458 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8459 if (!Invalid &&
8460 !Context.hasSameType(OldTD->getUnderlyingType(),
8461 NewTD->getUnderlyingType())) {
8462 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8463 // but we can't reasonably accept it.
8464 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8465 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8466 if (OldTD->getLocation().isValid())
8467 Diag(OldTD->getLocation(), diag::note_previous_definition);
8468 Invalid = true;
8469 }
8470 }
8471 }
8472
8473 // Merge any previous default template arguments into our parameters,
8474 // and check the parameter list.
8475 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8476 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008477 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008478
8479 TypeAliasTemplateDecl *NewDecl =
8480 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8481 Name.Identifier, TemplateParams,
8482 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008483 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008484
8485 NewDecl->setAccess(AS);
8486
8487 if (Invalid)
8488 NewDecl->setInvalidDecl();
8489 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008490 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008491
8492 NewND = NewDecl;
8493 } else {
8494 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8495 NewND = NewTD;
8496 }
Richard Smithdda56e42011-04-15 14:24:37 +00008497
8498 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008499 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008500
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008501 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008502 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008503}
8504
Richard Smithf4634362014-09-03 23:11:22 +00008505Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8506 SourceLocation AliasLoc,
8507 IdentifierInfo *Alias, CXXScopeSpec &SS,
8508 SourceLocation IdentLoc,
8509 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008510
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008511 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008512 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8513 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008514
John McCall27b18f82009-11-17 02:14:36 +00008515 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008516 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008517
John McCall9f3059a2009-10-09 21:13:30 +00008518 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008519 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008520 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008521 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008522 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008523 }
Richard Smithf4634362014-09-03 23:11:22 +00008524 assert(!R.isAmbiguous() && !R.empty());
8525
8526 // Check if we have a previous declaration with the same name.
8527 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8528 ForRedeclaration);
8529 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8530 PrevDecl = nullptr;
8531
Aaron Ballman43f40102014-11-14 22:34:56 +00008532 NamedDecl *ND = R.getFoundDecl();
8533
Richard Smithf4634362014-09-03 23:11:22 +00008534 if (PrevDecl) {
8535 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8536 // We already have an alias with the same name that points to the same
8537 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008538 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008539 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8540 << Alias;
8541 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8542 << AD->getNamespace();
8543 return nullptr;
8544 }
8545 } else {
8546 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8547 ? diag::err_redefinition
8548 : diag::err_redefinition_different_kind;
8549 Diag(AliasLoc, DiagID) << Alias;
8550 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8551 return nullptr;
8552 }
8553 }
Mike Stump11289f42009-09-09 15:08:12 +00008554
Nico Riecke50e59a2014-11-24 17:29:52 +00008555 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008556 DiagnoseUseOfDecl(ND, IdentLoc);
8557
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008558 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008559 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008560 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008561 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008562 if (PrevDecl)
8563 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008564
John McCalld8d0d432010-02-16 06:53:13 +00008565 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008566 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008567}
8568
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008569Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008570Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8571 CXXMethodDecl *MD) {
8572 CXXRecordDecl *ClassDecl = MD->getParent();
8573
Douglas Gregor6d880b12010-07-01 22:31:05 +00008574 // C++ [except.spec]p14:
8575 // An implicitly declared special member function (Clause 12) shall have an
8576 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008577 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008578 if (ClassDecl->isInvalidDecl())
8579 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008580
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008581 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008582 for (const auto &B : ClassDecl->bases()) {
8583 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008584 continue;
8585
Aaron Ballman574705e2014-03-13 15:41:46 +00008586 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008587 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008588 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8589 // If this is a deleted function, add it anyway. This might be conformant
8590 // with the standard. This might not. I'm not sure. It might not matter.
8591 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008592 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008593 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008594 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008595
8596 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008597 for (const auto &B : ClassDecl->vbases()) {
8598 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008599 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008600 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8601 // If this is a deleted function, add it anyway. This might be conformant
8602 // with the standard. This might not. I'm not sure. It might not matter.
8603 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008604 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008605 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008606 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008607
8608 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008609 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008610 if (F->hasInClassInitializer()) {
8611 if (Expr *E = F->getInClassInitializer())
8612 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008613 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008614 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008615 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8616 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8617 // If this is a deleted function, add it anyway. This might be conformant
8618 // with the standard. This might not. I'm not sure. It might not matter.
8619 // In particular, the problem is that this function never gets called. It
8620 // might just be ill-formed because this function attempts to refer to
8621 // a deleted function here.
8622 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008623 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008624 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008625 }
John McCalldb40c7f2010-12-14 08:05:40 +00008626
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008627 return ExceptSpec;
8628}
8629
Richard Smithc2bc61b2013-03-18 21:12:30 +00008630Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008631Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8632 CXXRecordDecl *ClassDecl = CD->getParent();
8633
8634 // C++ [except.spec]p14:
8635 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008636 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008637 if (ClassDecl->isInvalidDecl())
8638 return ExceptSpec;
8639
8640 // Inherited constructor.
8641 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8642 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8643 // FIXME: Copying or moving the parameters could add extra exceptions to the
8644 // set, as could the default arguments for the inherited constructor. This
8645 // will be addressed when we implement the resolution of core issue 1351.
8646 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8647
8648 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008649 for (const auto &B : ClassDecl->bases()) {
8650 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008651 continue;
8652
Aaron Ballman574705e2014-03-13 15:41:46 +00008653 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008654 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8655 if (BaseClassDecl == InheritedDecl)
8656 continue;
8657 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8658 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008659 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008660 }
8661 }
8662
8663 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008664 for (const auto &B : ClassDecl->vbases()) {
8665 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008666 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8667 if (BaseClassDecl == InheritedDecl)
8668 continue;
8669 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8670 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008671 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008672 }
8673 }
8674
8675 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008676 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008677 if (F->hasInClassInitializer()) {
8678 if (Expr *E = F->getInClassInitializer())
8679 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008680 } else if (const RecordType *RecordTy
8681 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8682 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8683 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8684 if (Constructor)
8685 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8686 }
8687 }
8688
Richard Smithc2bc61b2013-03-18 21:12:30 +00008689 return ExceptSpec;
8690}
8691
Richard Smith8bf22e52012-11-29 01:34:07 +00008692namespace {
8693/// RAII object to register a special member as being currently declared.
8694struct DeclaringSpecialMember {
8695 Sema &S;
8696 Sema::SpecialMemberDecl D;
8697 bool WasAlreadyBeingDeclared;
8698
8699 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8700 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008701 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008702 if (WasAlreadyBeingDeclared)
8703 // This almost never happens, but if it does, ensure that our cache
8704 // doesn't contain a stale result.
8705 S.SpecialMemberCache.clear();
8706
8707 // FIXME: Register a note to be produced if we encounter an error while
8708 // declaring the special member.
8709 }
8710 ~DeclaringSpecialMember() {
8711 if (!WasAlreadyBeingDeclared)
8712 S.SpecialMembersBeingDeclared.erase(D);
8713 }
8714
8715 /// \brief Are we already trying to declare this special member?
8716 bool isAlreadyBeingDeclared() const {
8717 return WasAlreadyBeingDeclared;
8718 }
8719};
8720}
8721
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008722CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8723 CXXRecordDecl *ClassDecl) {
8724 // C++ [class.ctor]p5:
8725 // A default constructor for a class X is a constructor of class X
8726 // that can be called without an argument. If there is no
8727 // user-declared constructor for class X, a default constructor is
8728 // implicitly declared. An implicitly-declared default constructor
8729 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008730 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008731 "Should not build implicit default constructor!");
8732
Richard Smith8bf22e52012-11-29 01:34:07 +00008733 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8734 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008735 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008736
Richard Smithb5800092012-06-10 05:43:50 +00008737 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8738 CXXDefaultConstructor,
8739 false);
8740
Douglas Gregor6d880b12010-07-01 22:31:05 +00008741 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008742 CanQualType ClassType
8743 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008744 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008745 DeclarationName Name
8746 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008747 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008748 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008749 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8750 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8751 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008752 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008753 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008754
8755 if (getLangOpts().CUDA) {
8756 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8757 DefaultCon,
8758 /* ConstRHS */ false,
8759 /* Diagnose */ false);
8760 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008761
8762 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008763 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008764 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008765
Richard Smith6b02d462012-12-08 08:32:28 +00008766 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8767 // constructors is easy to compute.
8768 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8769
8770 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008771 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008772
Douglas Gregor9672f922010-07-03 00:47:00 +00008773 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008774 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008775
Douglas Gregor0be31a22010-07-02 17:43:08 +00008776 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008777 PushOnScopeChains(DefaultCon, S, false);
8778 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008779
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008780 return DefaultCon;
8781}
8782
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008783void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8784 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008785 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008786 !Constructor->doesThisDeclarationHaveABody() &&
8787 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008788 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008789
Anders Carlsson423f5d82010-04-23 16:04:08 +00008790 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008791 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008792
Eli Friedmaneaf34142012-10-18 20:14:08 +00008793 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008794 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008795 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008796 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008797 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008798 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008799 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008800 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008801 }
Douglas Gregor73193272010-09-20 16:48:21 +00008802
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008803 // The exception specification is needed because we are defining the
8804 // function.
8805 ResolveExceptionSpec(CurrentLocation,
8806 Constructor->getType()->castAs<FunctionProtoType>());
8807
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008808 SourceLocation Loc = Constructor->getLocEnd().isValid()
8809 ? Constructor->getLocEnd()
8810 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008811 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008812
Eli Friedman276dd182013-09-05 00:02:25 +00008813 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008814 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008815
8816 if (ASTMutationListener *L = getASTMutationListener()) {
8817 L->CompletedImplicitDefinition(Constructor);
8818 }
Richard Trieuef64e942013-10-25 00:56:00 +00008819
8820 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008821}
8822
Richard Smith938f40b2011-06-11 17:19:42 +00008823void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008824 // Perform any delayed checks on exception specifications.
8825 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008826}
8827
Richard Smith185be182013-04-10 05:48:59 +00008828namespace {
8829/// Information on inheriting constructors to declare.
8830class InheritingConstructorInfo {
8831public:
8832 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8833 : SemaRef(SemaRef), Derived(Derived) {
8834 // Mark the constructors that we already have in the derived class.
8835 //
8836 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8837 // unless there is a user-declared constructor with the same signature in
8838 // the class where the using-declaration appears.
8839 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8840 }
8841
8842 void inheritAll(CXXRecordDecl *RD) {
8843 visitAll(RD, &InheritingConstructorInfo::inherit);
8844 }
8845
8846private:
8847 /// Information about an inheriting constructor.
8848 struct InheritingConstructor {
8849 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008850 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008851
8852 /// If \c true, a constructor with this signature is already declared
8853 /// in the derived class.
8854 bool DeclaredInDerived;
8855
8856 /// The constructor which is inherited.
8857 const CXXConstructorDecl *BaseCtor;
8858
8859 /// The derived constructor we declared.
8860 CXXConstructorDecl *DerivedCtor;
8861 };
8862
8863 /// Inheriting constructors with a given canonical type. There can be at
8864 /// most one such non-template constructor, and any number of templated
8865 /// constructors.
8866 struct InheritingConstructorsForType {
8867 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008868 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8869 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008870
8871 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8872 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8873 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8874 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8875 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8876 false, S.TPL_TemplateMatch))
8877 return Templates[I].second;
8878 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8879 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008880 }
Richard Smith185be182013-04-10 05:48:59 +00008881
8882 return NonTemplate;
8883 }
8884 };
8885
8886 /// Get or create the inheriting constructor record for a constructor.
8887 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8888 QualType CtorType) {
8889 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8890 .getEntry(SemaRef, Ctor);
8891 }
8892
8893 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8894
8895 /// Process all constructors for a class.
8896 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008897 for (const auto *Ctor : RD->ctors())
8898 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008899 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8900 I(RD->decls_begin()), E(RD->decls_end());
8901 I != E; ++I) {
8902 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8903 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8904 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008905 }
8906 }
Richard Smith185be182013-04-10 05:48:59 +00008907
8908 /// Note that a constructor (or constructor template) was declared in Derived.
8909 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8910 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8911 }
8912
8913 /// Inherit a single constructor.
8914 void inherit(const CXXConstructorDecl *Ctor) {
8915 const FunctionProtoType *CtorType =
8916 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00008917 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00008918 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8919
8920 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8921
8922 // Core issue (no number yet): the ellipsis is always discarded.
8923 if (EPI.Variadic) {
8924 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8925 SemaRef.Diag(Ctor->getLocation(),
8926 diag::note_using_decl_constructor_ellipsis);
8927 EPI.Variadic = false;
8928 }
8929
8930 // Declare a constructor for each number of parameters.
8931 //
8932 // C++11 [class.inhctor]p1:
8933 // The candidate set of inherited constructors from the class X named in
8934 // the using-declaration consists of [... modulo defects ...] for each
8935 // constructor or constructor template of X, the set of constructors or
8936 // constructor templates that results from omitting any ellipsis parameter
8937 // specification and successively omitting parameters with a default
8938 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008939 unsigned MinParams = minParamsToInherit(Ctor);
8940 unsigned Params = Ctor->getNumParams();
8941 if (Params >= MinParams) {
8942 do
8943 declareCtor(UsingLoc, Ctor,
8944 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008945 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008946 while (Params > MinParams &&
8947 Ctor->getParamDecl(--Params)->hasDefaultArg());
8948 }
Richard Smith185be182013-04-10 05:48:59 +00008949 }
8950
8951 /// Find the using-declaration which specified that we should inherit the
8952 /// constructors of \p Base.
8953 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8954 // No fancy lookup required; just look for the base constructor name
8955 // directly within the derived class.
8956 ASTContext &Context = SemaRef.Context;
8957 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8958 Context.getCanonicalType(Context.getRecordType(Base)));
8959 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8960 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8961 }
8962
8963 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8964 // C++11 [class.inhctor]p3:
8965 // [F]or each constructor template in the candidate set of inherited
8966 // constructors, a constructor template is implicitly declared
8967 if (Ctor->getDescribedFunctionTemplate())
8968 return 0;
8969
8970 // For each non-template constructor in the candidate set of inherited
8971 // constructors other than a constructor having no parameters or a
8972 // copy/move constructor having a single parameter, a constructor is
8973 // implicitly declared [...]
8974 if (Ctor->getNumParams() == 0)
8975 return 1;
8976 if (Ctor->isCopyOrMoveConstructor())
8977 return 2;
8978
8979 // Per discussion on core reflector, never inherit a constructor which
8980 // would become a default, copy, or move constructor of Derived either.
8981 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8982 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8983 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8984 }
8985
8986 /// Declare a single inheriting constructor, inheriting the specified
8987 /// constructor, with the given type.
8988 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8989 QualType DerivedType) {
8990 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8991
8992 // C++11 [class.inhctor]p3:
8993 // ... a constructor is implicitly declared with the same constructor
8994 // characteristics unless there is a user-declared constructor with
8995 // the same signature in the class where the using-declaration appears
8996 if (Entry.DeclaredInDerived)
8997 return;
8998
8999 // C++11 [class.inhctor]p7:
9000 // If two using-declarations declare inheriting constructors with the
9001 // same signature, the program is ill-formed
9002 if (Entry.DerivedCtor) {
9003 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9004 // Only diagnose this once per constructor.
9005 if (Entry.DerivedCtor->isInvalidDecl())
9006 return;
9007 Entry.DerivedCtor->setInvalidDecl();
9008
9009 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9010 SemaRef.Diag(BaseCtor->getLocation(),
9011 diag::note_using_decl_constructor_conflict_current_ctor);
9012 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9013 diag::note_using_decl_constructor_conflict_previous_ctor);
9014 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9015 diag::note_using_decl_constructor_conflict_previous_using);
9016 } else {
9017 // Core issue (no number): if the same inheriting constructor is
9018 // produced by multiple base class constructors from the same base
9019 // class, the inheriting constructor is defined as deleted.
9020 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9021 }
9022
9023 return;
9024 }
9025
9026 ASTContext &Context = SemaRef.Context;
9027 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9028 Context.getCanonicalType(Context.getRecordType(Derived)));
9029 DeclarationNameInfo NameInfo(Name, UsingLoc);
9030
Craig Topperc3ec1492014-05-26 06:22:03 +00009031 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009032 if (const FunctionTemplateDecl *FTD =
9033 BaseCtor->getDescribedFunctionTemplate()) {
9034 TemplateParams = FTD->getTemplateParameters();
9035 // We're reusing template parameters from a different DeclContext. This
9036 // is questionable at best, but works out because the template depth in
9037 // both places is guaranteed to be 0.
9038 // FIXME: Rebuild the template parameters in the new context, and
9039 // transform the function type to refer to them.
9040 }
9041
9042 // Build type source info pointing at the using-declaration. This is
9043 // required by template instantiation.
9044 TypeSourceInfo *TInfo =
9045 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9046 FunctionProtoTypeLoc ProtoLoc =
9047 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9048
9049 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9050 Context, Derived, UsingLoc, NameInfo, DerivedType,
9051 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9052 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9053
9054 // Build an unevaluated exception specification for this constructor.
9055 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9056 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009057 EPI.ExceptionSpec.Type = EST_Unevaluated;
9058 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009059 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009060 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009061
9062 // Build the parameter declarations.
9063 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009064 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009065 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009066 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009067 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009068 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9069 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009070 PD->setScopeInfo(0, I);
9071 PD->setImplicit();
9072 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009073 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009074 }
9075
9076 // Set up the new constructor.
9077 DerivedCtor->setAccess(BaseCtor->getAccess());
9078 DerivedCtor->setParams(ParamDecls);
9079 DerivedCtor->setInheritedConstructor(BaseCtor);
9080 if (BaseCtor->isDeleted())
9081 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9082
9083 // If this is a constructor template, build the template declaration.
9084 if (TemplateParams) {
9085 FunctionTemplateDecl *DerivedTemplate =
9086 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9087 TemplateParams, DerivedCtor);
9088 DerivedTemplate->setAccess(BaseCtor->getAccess());
9089 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9090 Derived->addDecl(DerivedTemplate);
9091 } else {
9092 Derived->addDecl(DerivedCtor);
9093 }
9094
9095 Entry.BaseCtor = BaseCtor;
9096 Entry.DerivedCtor = DerivedCtor;
9097 }
9098
9099 Sema &SemaRef;
9100 CXXRecordDecl *Derived;
9101 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9102 MapType Map;
9103};
9104}
9105
9106void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9107 // Defer declaring the inheriting constructors until the class is
9108 // instantiated.
9109 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009110 return;
9111
Richard Smith185be182013-04-10 05:48:59 +00009112 // Find base classes from which we might inherit constructors.
9113 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009114 for (const auto &BaseIt : ClassDecl->bases())
9115 if (BaseIt.getInheritConstructors())
9116 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009117
Richard Smith185be182013-04-10 05:48:59 +00009118 // Go no further if we're not inheriting any constructors.
9119 if (InheritedBases.empty())
9120 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009121
Richard Smith185be182013-04-10 05:48:59 +00009122 // Declare the inherited constructors.
9123 InheritingConstructorInfo ICI(*this, ClassDecl);
9124 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9125 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009126}
9127
Richard Smithc2bc61b2013-03-18 21:12:30 +00009128void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9129 CXXConstructorDecl *Constructor) {
9130 CXXRecordDecl *ClassDecl = Constructor->getParent();
9131 assert(Constructor->getInheritedConstructor() &&
9132 !Constructor->doesThisDeclarationHaveABody() &&
9133 !Constructor->isDeleted());
9134
9135 SynthesizedFunctionScope Scope(*this, Constructor);
9136 DiagnosticErrorTrap Trap(Diags);
9137 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9138 Trap.hasErrorOccurred()) {
9139 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9140 << Context.getTagDeclType(ClassDecl);
9141 Constructor->setInvalidDecl();
9142 return;
9143 }
9144
9145 SourceLocation Loc = Constructor->getLocation();
9146 Constructor->setBody(new (Context) CompoundStmt(Loc));
9147
Eli Friedman276dd182013-09-05 00:02:25 +00009148 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009149 MarkVTableUsed(CurrentLocation, ClassDecl);
9150
9151 if (ASTMutationListener *L = getASTMutationListener()) {
9152 L->CompletedImplicitDefinition(Constructor);
9153 }
9154}
9155
9156
Alexis Huntf91729462011-05-12 22:46:25 +00009157Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009158Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9159 CXXRecordDecl *ClassDecl = MD->getParent();
9160
Douglas Gregorf1203042010-07-01 19:09:28 +00009161 // C++ [except.spec]p14:
9162 // An implicitly declared special member function (Clause 12) shall have
9163 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009164 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009165 if (ClassDecl->isInvalidDecl())
9166 return ExceptSpec;
9167
Douglas Gregorf1203042010-07-01 19:09:28 +00009168 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009169 for (const auto &B : ClassDecl->bases()) {
9170 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009171 continue;
9172
Aaron Ballman574705e2014-03-13 15:41:46 +00009173 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9174 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009175 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009176 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009177
Douglas Gregorf1203042010-07-01 19:09:28 +00009178 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009179 for (const auto &B : ClassDecl->vbases()) {
9180 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9181 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009182 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009183 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009184
Douglas Gregorf1203042010-07-01 19:09:28 +00009185 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009186 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009187 if (const RecordType *RecordTy
9188 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009189 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009190 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009191 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009192
Alexis Huntf91729462011-05-12 22:46:25 +00009193 return ExceptSpec;
9194}
9195
9196CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9197 // C++ [class.dtor]p2:
9198 // If a class has no user-declared destructor, a destructor is
9199 // declared implicitly. An implicitly-declared destructor is an
9200 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009201 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009202
Richard Smith8bf22e52012-11-29 01:34:07 +00009203 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9204 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009205 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009206
Douglas Gregor7454c562010-07-02 20:37:36 +00009207 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009208 CanQualType ClassType
9209 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009210 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009211 DeclarationName Name
9212 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009213 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009214 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009215 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009216 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009217 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009218 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009219 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009220
9221 if (getLangOpts().CUDA) {
9222 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9223 Destructor,
9224 /* ConstRHS */ false,
9225 /* Diagnose */ false);
9226 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009227
9228 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009229 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009230 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009231
Richard Smith6b02d462012-12-08 08:32:28 +00009232 AddOverriddenMethods(ClassDecl, Destructor);
9233
9234 // We don't need to use SpecialMemberIsTrivial here; triviality for
9235 // destructors is easy to compute.
9236 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9237
9238 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009239 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009240
Douglas Gregor7454c562010-07-02 20:37:36 +00009241 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009242 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009243
Douglas Gregor7454c562010-07-02 20:37:36 +00009244 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009245 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009246 PushOnScopeChains(Destructor, S, false);
9247 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009248
Douglas Gregorf1203042010-07-01 19:09:28 +00009249 return Destructor;
9250}
9251
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009252void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009253 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009254 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009255 !Destructor->doesThisDeclarationHaveABody() &&
9256 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009257 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009258 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009259 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009260
Douglas Gregor54818f02010-05-12 16:39:35 +00009261 if (Destructor->isInvalidDecl())
9262 return;
9263
Eli Friedmaneaf34142012-10-18 20:14:08 +00009264 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009265
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009266 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009267 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9268 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009269
Douglas Gregor54818f02010-05-12 16:39:35 +00009270 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009271 Diag(CurrentLocation, diag::note_member_synthesized_at)
9272 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9273
9274 Destructor->setInvalidDecl();
9275 return;
9276 }
9277
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009278 // The exception specification is needed because we are defining the
9279 // function.
9280 ResolveExceptionSpec(CurrentLocation,
9281 Destructor->getType()->castAs<FunctionProtoType>());
9282
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009283 SourceLocation Loc = Destructor->getLocEnd().isValid()
9284 ? Destructor->getLocEnd()
9285 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009286 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009287 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009288 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009289
9290 if (ASTMutationListener *L = getASTMutationListener()) {
9291 L->CompletedImplicitDefinition(Destructor);
9292 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009293}
9294
Richard Smith84973e52012-04-21 18:42:51 +00009295/// \brief Perform any semantic analysis which needs to be delayed until all
9296/// pending class member declarations have been parsed.
9297void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009298 // If the context is an invalid C++ class, just suppress these checks.
9299 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9300 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009301 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009302 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009303 return;
9304 }
9305 }
Richard Smith84973e52012-04-21 18:42:51 +00009306}
9307
Richard Smithd3b5c9082012-07-27 04:22:15 +00009308void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9309 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009310 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009311 "adjusting dtor exception specs was introduced in c++11");
9312
Sebastian Redl623ea822011-05-19 05:13:44 +00009313 // C++11 [class.dtor]p3:
9314 // A declaration of a destructor that does not have an exception-
9315 // specification is implicitly considered to have the same exception-
9316 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009317 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009318 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009319 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009320 return;
9321
Chandler Carruth9a797572011-09-20 04:55:26 +00009322 // Replace the destructor's type, building off the existing one. Fortunately,
9323 // the only thing of interest in the destructor type is its extended info.
9324 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009325 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009326 EPI.ExceptionSpec.Type = EST_Unevaluated;
9327 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009328 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009329
Sebastian Redl623ea822011-05-19 05:13:44 +00009330 // FIXME: If the destructor has a body that could throw, and the newly created
9331 // spec doesn't allow exceptions, we should emit a warning, because this
9332 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009333 // However, we don't have a body or an exception specification yet, so it
9334 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009335}
9336
Pavel Labath58934982013-08-30 08:52:28 +00009337namespace {
9338/// \brief An abstract base class for all helper classes used in building the
9339// copy/move operators. These classes serve as factory functions and help us
9340// avoid using the same Expr* in the AST twice.
9341class ExprBuilder {
9342 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9343 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9344
9345protected:
9346 static Expr *assertNotNull(Expr *E) {
9347 assert(E && "Expression construction must not fail.");
9348 return E;
9349 }
9350
9351public:
9352 ExprBuilder() {}
9353 virtual ~ExprBuilder() {}
9354
9355 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9356};
9357
9358class RefBuilder: public ExprBuilder {
9359 VarDecl *Var;
9360 QualType VarType;
9361
9362public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009363 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009364 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009365 }
9366
9367 RefBuilder(VarDecl *Var, QualType VarType)
9368 : Var(Var), VarType(VarType) {}
9369};
9370
9371class ThisBuilder: public ExprBuilder {
9372public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009373 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009374 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009375 }
9376};
9377
9378class CastBuilder: public ExprBuilder {
9379 const ExprBuilder &Builder;
9380 QualType Type;
9381 ExprValueKind Kind;
9382 const CXXCastPath &Path;
9383
9384public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009385 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009386 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9387 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009388 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009389 }
9390
9391 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9392 const CXXCastPath &Path)
9393 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9394};
9395
9396class DerefBuilder: public ExprBuilder {
9397 const ExprBuilder &Builder;
9398
9399public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009400 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009401 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009402 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009403 }
9404
9405 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9406};
9407
9408class MemberBuilder: public ExprBuilder {
9409 const ExprBuilder &Builder;
9410 QualType Type;
9411 CXXScopeSpec SS;
9412 bool IsArrow;
9413 LookupResult &MemberLookup;
9414
9415public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009416 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009417 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009418 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009419 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009420 }
9421
9422 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9423 LookupResult &MemberLookup)
9424 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9425 MemberLookup(MemberLookup) {}
9426};
9427
9428class MoveCastBuilder: public ExprBuilder {
9429 const ExprBuilder &Builder;
9430
9431public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009432 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009433 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9434 }
9435
9436 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9437};
9438
9439class LvalueConvBuilder: public ExprBuilder {
9440 const ExprBuilder &Builder;
9441
9442public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009443 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009444 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009445 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009446 }
9447
9448 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9449};
9450
9451class SubscriptBuilder: public ExprBuilder {
9452 const ExprBuilder &Base;
9453 const ExprBuilder &Index;
9454
9455public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009456 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009457 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009458 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009459 }
9460
9461 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9462 : Base(Base), Index(Index) {}
9463};
9464
9465} // end anonymous namespace
9466
Richard Smith41ae3282012-11-14 00:50:40 +00009467/// When generating a defaulted copy or move assignment operator, if a field
9468/// should be copied with __builtin_memcpy rather than via explicit assignments,
9469/// do so. This optimization only applies for arrays of scalars, and for arrays
9470/// of class type where the selected copy/move-assignment operator is trivial.
9471static StmtResult
9472buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009473 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009474 // Compute the size of the memory buffer to be copied.
9475 QualType SizeType = S.Context.getSizeType();
9476 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9477 S.Context.getTypeSizeInChars(T).getQuantity());
9478
9479 // Take the address of the field references for "from" and "to". We
9480 // directly construct UnaryOperators here because semantic analysis
9481 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009482 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009483 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9484 S.Context.getPointerType(From->getType()),
9485 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009486 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009487 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9488 S.Context.getPointerType(To->getType()),
9489 VK_RValue, OK_Ordinary, Loc);
9490
9491 const Type *E = T->getBaseElementTypeUnsafe();
9492 bool NeedsCollectableMemCpy =
9493 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9494
9495 // Create a reference to the __builtin_objc_memmove_collectable function
9496 StringRef MemCpyName = NeedsCollectableMemCpy ?
9497 "__builtin_objc_memmove_collectable" :
9498 "__builtin_memcpy";
9499 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9500 Sema::LookupOrdinaryName);
9501 S.LookupName(R, S.TUScope, true);
9502
9503 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9504 if (!MemCpy)
9505 // Something went horribly wrong earlier, and we will have complained
9506 // about it.
9507 return StmtError();
9508
9509 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009510 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009511 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9512
9513 Expr *CallArgs[] = {
9514 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9515 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009516 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009517 Loc, CallArgs, Loc);
9518
9519 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009520 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009521}
9522
Sebastian Redl22653ba2011-08-30 19:58:05 +00009523/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009524/// \c To.
9525///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009526/// This routine is used to copy/move the members of a class with an
9527/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009528/// copied are arrays, this routine builds for loops to copy them.
9529///
9530/// \param S The Sema object used for type-checking.
9531///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009532/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009533///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009534/// \param T The type of the expressions being copied/moved. Both expressions
9535/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009536///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009537/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009538///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009539/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009540///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009541/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009542/// Otherwise, it's a non-static member subobject.
9543///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009544/// \param Copying Whether we're copying or moving.
9545///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009546/// \param Depth Internal parameter recording the depth of the recursion.
9547///
Richard Smith41ae3282012-11-14 00:50:40 +00009548/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9549/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009550static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009551buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009552 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009553 bool CopyingBaseSubobject, bool Copying,
9554 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009555 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009556 // Each subobject is assigned in the manner appropriate to its type:
9557 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009558 // - if the subobject is of class type, as if by a call to operator= with
9559 // the subobject as the object expression and the corresponding
9560 // subobject of x as a single function argument (as if by explicit
9561 // qualification; that is, ignoring any possible virtual overriding
9562 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009563 //
9564 // C++03 [class.copy]p13:
9565 // - if the subobject is of class type, the copy assignment operator for
9566 // the class is used (as if by explicit qualification; that is,
9567 // ignoring any possible virtual overriding functions in more derived
9568 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009569 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9570 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009571
Douglas Gregorb139cd52010-05-01 20:49:11 +00009572 // Look for operator=.
9573 DeclarationName Name
9574 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9575 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9576 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009577
Richard Smith52c0b582012-11-13 00:54:12 +00009578 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9579 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009580 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009581 LookupResult::Filter F = OpLookup.makeFilter();
9582 while (F.hasNext()) {
9583 NamedDecl *D = F.next();
9584 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9585 if (Method->isCopyAssignmentOperator() ||
9586 (!Copying && Method->isMoveAssignmentOperator()))
9587 continue;
9588
9589 F.erase();
9590 }
9591 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009592 }
Richard Smith52c0b582012-11-13 00:54:12 +00009593
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009594 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009595 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009596 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009597 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009598 // ambiguities), we need to cast "this" to that subobject type; to
9599 // ensure that we don't go through the virtual call mechanism, we need
9600 // to qualify the operator= name with the base class (see below). However,
9601 // this means that if the base class has a protected copy assignment
9602 // operator, the protected member access check will fail. So, we
9603 // rewrite "protected" access to "public" access in this case, since we
9604 // know by construction that we're calling from a derived class.
9605 if (CopyingBaseSubobject) {
9606 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9607 L != LEnd; ++L) {
9608 if (L.getAccess() == AS_protected)
9609 L.setAccess(AS_public);
9610 }
9611 }
Richard Smith52c0b582012-11-13 00:54:12 +00009612
Douglas Gregorb139cd52010-05-01 20:49:11 +00009613 // Create the nested-name-specifier that will be used to qualify the
9614 // reference to operator=; this is required to suppress the virtual
9615 // call mechanism.
9616 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009617 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009618 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009619 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009620 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009621 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009622
Douglas Gregorb139cd52010-05-01 20:49:11 +00009623 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009624 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009625 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9626 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009627 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009628 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009629 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009630 /*SuppressQualifierCheck=*/true);
9631 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009632 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009633
Douglas Gregorb139cd52010-05-01 20:49:11 +00009634 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009635
Pavel Labath58934982013-08-30 08:52:28 +00009636 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009637 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009638 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009639 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009640 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009641 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009642
Richard Smith41ae3282012-11-14 00:50:40 +00009643 // If we built a call to a trivial 'operator=' while copying an array,
9644 // bail out. We'll replace the whole shebang with a memcpy.
9645 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9646 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009647 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009648
Richard Smith52c0b582012-11-13 00:54:12 +00009649 // Convert to an expression-statement, and clean up any produced
9650 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009651 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009652 }
John McCallab8c2732010-03-16 06:11:48 +00009653
Richard Smith52c0b582012-11-13 00:54:12 +00009654 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009655 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009656 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009657 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009658 ExprResult Assignment = S.CreateBuiltinBinOp(
9659 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009660 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009661 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009662 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009663 }
Richard Smith52c0b582012-11-13 00:54:12 +00009664
9665 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009666 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009667
Douglas Gregorb139cd52010-05-01 20:49:11 +00009668 // Construct a loop over the array bounds, e.g.,
9669 //
9670 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9671 //
9672 // that will copy each of the array elements.
9673 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009674
Douglas Gregorb139cd52010-05-01 20:49:11 +00009675 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009676 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009677 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009678 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009679 llvm::raw_svector_ostream OS(Str);
9680 OS << "__i" << Depth;
9681 IterationVarName = &S.Context.Idents.get(OS.str());
9682 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009683 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009684 IterationVarName, SizeType,
9685 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009686 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009687
Douglas Gregorb139cd52010-05-01 20:49:11 +00009688 // Initialize the iteration variable to zero.
9689 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009690 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009691
Pavel Labath58934982013-08-30 08:52:28 +00009692 // Creates a reference to the iteration variable.
9693 RefBuilder IterationVarRef(IterationVar, SizeType);
9694 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009695
Douglas Gregorb139cd52010-05-01 20:49:11 +00009696 // Create the DeclStmt that holds the iteration variable.
9697 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009698
Douglas Gregorb139cd52010-05-01 20:49:11 +00009699 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009700 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9701 MoveCastBuilder FromIndexMove(FromIndexCopy);
9702 const ExprBuilder *FromIndex;
9703 if (Copying)
9704 FromIndex = &FromIndexCopy;
9705 else
9706 FromIndex = &FromIndexMove;
9707
9708 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009709
9710 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009711 StmtResult Copy =
9712 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009713 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009714 Copying, Depth + 1);
9715 // Bail out if copying fails or if we determined that we should use memcpy.
9716 if (Copy.isInvalid() || !Copy.get())
9717 return Copy;
9718
9719 // Create the comparison against the array bound.
9720 llvm::APInt Upper
9721 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9722 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009723 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009724 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9725 BO_NE, S.Context.BoolTy,
9726 VK_RValue, OK_Ordinary, Loc, false);
9727
9728 // Create the pre-increment of the iteration variable.
9729 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009730 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9731 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009732
Douglas Gregorb139cd52010-05-01 20:49:11 +00009733 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009734 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009735 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009736 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009737 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009738}
9739
Richard Smith41ae3282012-11-14 00:50:40 +00009740static StmtResult
9741buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009742 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009743 bool CopyingBaseSubobject, bool Copying) {
9744 // Maybe we should use a memcpy?
9745 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9746 T.isTriviallyCopyableType(S.Context))
9747 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9748
9749 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9750 CopyingBaseSubobject,
9751 Copying, 0));
9752
9753 // If we ended up picking a trivial assignment operator for an array of a
9754 // non-trivially-copyable class type, just emit a memcpy.
9755 if (!Result.isInvalid() && !Result.get())
9756 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9757
9758 return Result;
9759}
9760
Richard Smithd3b5c9082012-07-27 04:22:15 +00009761Sema::ImplicitExceptionSpecification
9762Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9763 CXXRecordDecl *ClassDecl = MD->getParent();
9764
9765 ImplicitExceptionSpecification ExceptSpec(*this);
9766 if (ClassDecl->isInvalidDecl())
9767 return ExceptSpec;
9768
9769 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009770 assert(T->getNumParams() == 1 && "not a copy assignment op");
9771 unsigned ArgQuals =
9772 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009773
Douglas Gregor68e11362010-07-01 17:48:08 +00009774 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009775 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009776 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009777
9778 // It is unspecified whether or not an implicit copy assignment operator
9779 // attempts to deduplicate calls to assignment operators of virtual bases are
9780 // made. As such, this exception specification is effectively unspecified.
9781 // Based on a similar decision made for constness in C++0x, we're erring on
9782 // the side of assuming such calls to be made regardless of whether they
9783 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009784 for (const auto &Base : ClassDecl->bases()) {
9785 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009786 continue;
9787
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009788 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009789 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009790 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9791 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009792 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009793 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009794
Aaron Ballman445a9392014-03-13 16:15:17 +00009795 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009796 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009797 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009798 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9799 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009800 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009801 }
9802
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009803 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009804 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009805 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9806 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009807 LookupCopyingAssignment(FieldClassDecl,
9808 ArgQuals | FieldType.getCVRQualifiers(),
9809 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009810 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009811 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009812 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009813
Richard Smithd3b5c9082012-07-27 04:22:15 +00009814 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009815}
9816
9817CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9818 // Note: The following rules are largely analoguous to the copy
9819 // constructor rules. Note that virtual bases are not taken into account
9820 // for determining the argument type of the operator. Note also that
9821 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009822 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009823
Richard Smith8bf22e52012-11-29 01:34:07 +00009824 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9825 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009826 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009827
Alexis Hunt119f3652011-05-14 05:23:20 +00009828 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9829 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009830 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9831 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009832 ArgType = ArgType.withConst();
9833 ArgType = Context.getLValueReferenceType(ArgType);
9834
Richard Smith99005e62013-05-07 03:19:20 +00009835 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9836 CXXCopyAssignment,
9837 Const);
9838
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009839 // An implicitly-declared copy assignment operator is an inline public
9840 // member of its class.
9841 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009842 SourceLocation ClassLoc = ClassDecl->getLocation();
9843 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009844 CXXMethodDecl *CopyAssignment =
9845 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009846 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9847 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009848 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009849 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009850 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009851
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009852 if (getLangOpts().CUDA) {
9853 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9854 CopyAssignment,
9855 /* ConstRHS */ Const,
9856 /* Diagnose */ false);
9857 }
9858
Richard Smithd3b5c9082012-07-27 04:22:15 +00009859 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009860 FunctionProtoType::ExtProtoInfo EPI =
9861 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009862 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009863
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009864 // Add the parameter to the operator.
9865 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009866 ClassLoc, ClassLoc,
9867 /*Id=*/nullptr, ArgType,
9868 /*TInfo=*/nullptr, SC_None,
9869 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009870 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009871
Richard Smith6b02d462012-12-08 08:32:28 +00009872 AddOverriddenMethods(ClassDecl, CopyAssignment);
9873
9874 CopyAssignment->setTrivial(
9875 ClassDecl->needsOverloadResolutionForCopyAssignment()
9876 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9877 : ClassDecl->hasTrivialCopyAssignment());
9878
Richard Smith852265f2012-03-30 20:53:28 +00009879 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009880 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009881
Richard Smith6b02d462012-12-08 08:32:28 +00009882 // Note that we have added this copy-assignment operator.
9883 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9884
9885 if (Scope *S = getScopeForContext(ClassDecl))
9886 PushOnScopeChains(CopyAssignment, S, false);
9887 ClassDecl->addDecl(CopyAssignment);
9888
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009889 return CopyAssignment;
9890}
9891
Richard Smithd577fbb2013-06-13 03:23:42 +00009892/// Diagnose an implicit copy operation for a class which is odr-used, but
9893/// which is deprecated because the class has a user-declared copy constructor,
9894/// copy assignment operator, or destructor.
9895static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9896 SourceLocation UseLoc) {
9897 assert(CopyOp->isImplicit());
9898
9899 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009900 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009901
9902 // In Microsoft mode, assignment operations don't affect constructors and
9903 // vice versa.
9904 if (RD->hasUserDeclaredDestructor()) {
9905 UserDeclaredOperation = RD->getDestructor();
9906 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9907 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009908 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009909 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009910 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009911 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009912 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009913 break;
9914 }
9915 }
9916 assert(UserDeclaredOperation);
9917 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9918 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009919 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009920 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009921 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009922 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009923 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009924 break;
9925 }
9926 }
9927 assert(UserDeclaredOperation);
9928 }
9929
9930 if (UserDeclaredOperation) {
9931 S.Diag(UserDeclaredOperation->getLocation(),
9932 diag::warn_deprecated_copy_operation)
9933 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9934 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9935 S.Diag(UseLoc, diag::note_member_synthesized_at)
9936 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9937 : Sema::CXXCopyAssignment)
9938 << RD;
9939 }
9940}
9941
Douglas Gregorb139cd52010-05-01 20:49:11 +00009942void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9943 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009944 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009945 CopyAssignOperator->isOverloadedOperator() &&
9946 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009947 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9948 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009949 "DefineImplicitCopyAssignment called for wrong function");
9950
9951 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9952
9953 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9954 CopyAssignOperator->setInvalidDecl();
9955 return;
9956 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009957
9958 // C++11 [class.copy]p18:
9959 // The [definition of an implicitly declared copy assignment operator] is
9960 // deprecated if the class has a user-declared copy constructor or a
9961 // user-declared destructor.
9962 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9963 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9964
Eli Friedman276dd182013-09-05 00:02:25 +00009965 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009966
Eli Friedmaneaf34142012-10-18 20:14:08 +00009967 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009968 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009969
9970 // C++0x [class.copy]p30:
9971 // The implicitly-defined or explicitly-defaulted copy assignment operator
9972 // for a non-union class X performs memberwise copy assignment of its
9973 // subobjects. The direct base classes of X are assigned first, in the
9974 // order of their declaration in the base-specifier-list, and then the
9975 // immediate non-static data members of X are assigned, in the order in
9976 // which they were declared in the class definition.
9977
9978 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009979 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009980
9981 // The parameter for the "other" object, which we are copying from.
9982 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9983 Qualifiers OtherQuals = Other->getType().getQualifiers();
9984 QualType OtherRefType = Other->getType();
9985 if (const LValueReferenceType *OtherRef
9986 = OtherRefType->getAs<LValueReferenceType>()) {
9987 OtherRefType = OtherRef->getPointeeType();
9988 OtherQuals = OtherRefType.getQualifiers();
9989 }
9990
9991 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009992 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9993 ? CopyAssignOperator->getLocEnd()
9994 : CopyAssignOperator->getLocation();
9995
Pavel Labath58934982013-08-30 08:52:28 +00009996 // Builds a DeclRefExpr for the "other" object.
9997 RefBuilder OtherRef(Other, OtherRefType);
9998
9999 // Builds the "this" pointer.
10000 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010001
10002 // Assign base classes.
10003 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010004 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010005 // Form the assignment:
10006 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010007 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010008 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010009 Invalid = true;
10010 continue;
10011 }
10012
John McCallcf142162010-08-07 06:22:56 +000010013 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010014 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010015
Douglas Gregorb139cd52010-05-01 20:49:11 +000010016 // Construct the "from" expression, which is an implicit cast to the
10017 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010018 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10019 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010020
10021 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010022 DerefBuilder DerefThis(This);
10023 CastBuilder To(DerefThis,
10024 Context.getCVRQualifiedType(
10025 BaseType, CopyAssignOperator->getTypeQualifiers()),
10026 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010027
10028 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010029 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010030 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010031 /*CopyingBaseSubobject=*/true,
10032 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010033 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010034 Diag(CurrentLocation, diag::note_member_synthesized_at)
10035 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10036 CopyAssignOperator->setInvalidDecl();
10037 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010038 }
10039
10040 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010041 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010042 }
10043
Douglas Gregorb139cd52010-05-01 20:49:11 +000010044 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010045 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010046 if (Field->isUnnamedBitfield())
10047 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010048
10049 if (Field->isInvalidDecl()) {
10050 Invalid = true;
10051 continue;
10052 }
10053
Douglas Gregorb139cd52010-05-01 20:49:11 +000010054 // Check for members of reference type; we can't copy those.
10055 if (Field->getType()->isReferenceType()) {
10056 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10057 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10058 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010059 Diag(CurrentLocation, diag::note_member_synthesized_at)
10060 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010061 Invalid = true;
10062 continue;
10063 }
10064
10065 // Check for members of const-qualified, non-class type.
10066 QualType BaseType = Context.getBaseElementType(Field->getType());
10067 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10068 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10069 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10070 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010071 Diag(CurrentLocation, diag::note_member_synthesized_at)
10072 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010073 Invalid = true;
10074 continue;
10075 }
John McCall1b1a1db2011-06-17 00:18:42 +000010076
10077 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010078 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10079 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010080
10081 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010082 if (FieldType->isIncompleteArrayType()) {
10083 assert(ClassDecl->hasFlexibleArrayMember() &&
10084 "Incomplete array type is not valid");
10085 continue;
10086 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010087
10088 // Build references to the field in the object we're copying from and to.
10089 CXXScopeSpec SS; // Intentionally empty
10090 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10091 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010092 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010093 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010094
10095 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10096
10097 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010098
Douglas Gregorb139cd52010-05-01 20:49:11 +000010099 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010100 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010101 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010102 /*CopyingBaseSubobject=*/false,
10103 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010104 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010105 Diag(CurrentLocation, diag::note_member_synthesized_at)
10106 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10107 CopyAssignOperator->setInvalidDecl();
10108 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010109 }
10110
10111 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010112 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010113 }
10114
10115 if (!Invalid) {
10116 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010117 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010118
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010119 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010120 if (Return.isInvalid())
10121 Invalid = true;
10122 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010123 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010124
10125 if (Trap.hasErrorOccurred()) {
10126 Diag(CurrentLocation, diag::note_member_synthesized_at)
10127 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10128 Invalid = true;
10129 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010130 }
10131 }
10132
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010133 // The exception specification is needed because we are defining the
10134 // function.
10135 ResolveExceptionSpec(CurrentLocation,
10136 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10137
Douglas Gregorb139cd52010-05-01 20:49:11 +000010138 if (Invalid) {
10139 CopyAssignOperator->setInvalidDecl();
10140 return;
10141 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010142
10143 StmtResult Body;
10144 {
10145 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010146 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010147 /*isStmtExpr=*/false);
10148 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10149 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010150 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010151
10152 if (ASTMutationListener *L = getASTMutationListener()) {
10153 L->CompletedImplicitDefinition(CopyAssignOperator);
10154 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010155}
10156
Sebastian Redl22653ba2011-08-30 19:58:05 +000010157Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010158Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10159 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010160
Richard Smithd3b5c9082012-07-27 04:22:15 +000010161 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010162 if (ClassDecl->isInvalidDecl())
10163 return ExceptSpec;
10164
10165 // C++0x [except.spec]p14:
10166 // An implicitly declared special member function (Clause 12) shall have an
10167 // exception-specification. [...]
10168
10169 // It is unspecified whether or not an implicit move assignment operator
10170 // attempts to deduplicate calls to assignment operators of virtual bases are
10171 // made. As such, this exception specification is effectively unspecified.
10172 // Based on a similar decision made for constness in C++0x, we're erring on
10173 // the side of assuming such calls to be made regardless of whether they
10174 // actually happen.
10175 // Note that a move constructor is not implicitly declared when there are
10176 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010177 for (const auto &Base : ClassDecl->bases()) {
10178 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010179 continue;
10180
10181 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010182 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010183 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010184 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010185 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010186 }
10187
Aaron Ballman445a9392014-03-13 16:15:17 +000010188 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010189 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010190 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010191 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010192 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010193 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194 }
10195
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010196 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010197 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010198 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010199 if (CXXMethodDecl *MoveAssign =
10200 LookupMovingAssignment(FieldClassDecl,
10201 FieldType.getCVRQualifiers(),
10202 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010203 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010204 }
10205 }
10206
10207 return ExceptSpec;
10208}
10209
10210CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010211 assert(ClassDecl->needsImplicitMoveAssignment());
10212
Richard Smith8bf22e52012-11-29 01:34:07 +000010213 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10214 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010215 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010216
Sebastian Redl22653ba2011-08-30 19:58:05 +000010217 // Note: The following rules are largely analoguous to the move
10218 // constructor rules.
10219
Sebastian Redl22653ba2011-08-30 19:58:05 +000010220 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10221 QualType RetType = Context.getLValueReferenceType(ArgType);
10222 ArgType = Context.getRValueReferenceType(ArgType);
10223
Richard Smith99005e62013-05-07 03:19:20 +000010224 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10225 CXXMoveAssignment,
10226 false);
10227
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 // An implicitly-declared move assignment operator is an inline public
10229 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010230 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10231 SourceLocation ClassLoc = ClassDecl->getLocation();
10232 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010233 CXXMethodDecl *MoveAssignment =
10234 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010235 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010236 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010237 MoveAssignment->setAccess(AS_public);
10238 MoveAssignment->setDefaulted();
10239 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010240
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010241 if (getLangOpts().CUDA) {
10242 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10243 MoveAssignment,
10244 /* ConstRHS */ false,
10245 /* Diagnose */ false);
10246 }
10247
Richard Smithd3b5c9082012-07-27 04:22:15 +000010248 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010249 FunctionProtoType::ExtProtoInfo EPI =
10250 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010251 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010252
Sebastian Redl22653ba2011-08-30 19:58:05 +000010253 // Add the parameter to the operator.
10254 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010255 ClassLoc, ClassLoc,
10256 /*Id=*/nullptr, ArgType,
10257 /*TInfo=*/nullptr, SC_None,
10258 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010259 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010260
Richard Smith6b02d462012-12-08 08:32:28 +000010261 AddOverriddenMethods(ClassDecl, MoveAssignment);
10262
10263 MoveAssignment->setTrivial(
10264 ClassDecl->needsOverloadResolutionForMoveAssignment()
10265 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10266 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010267
Richard Smithd951a1d2012-02-18 02:02:13 +000010268 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010269 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10270 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010271 }
10272
Richard Smith6b02d462012-12-08 08:32:28 +000010273 // Note that we have added this copy-assignment operator.
10274 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10275
Sebastian Redl22653ba2011-08-30 19:58:05 +000010276 if (Scope *S = getScopeForContext(ClassDecl))
10277 PushOnScopeChains(MoveAssignment, S, false);
10278 ClassDecl->addDecl(MoveAssignment);
10279
Sebastian Redl22653ba2011-08-30 19:58:05 +000010280 return MoveAssignment;
10281}
10282
Richard Smithb2504bd2013-11-04 04:26:14 +000010283/// Check if we're implicitly defining a move assignment operator for a class
10284/// with virtual bases. Such a move assignment might move-assign the virtual
10285/// base multiple times.
10286static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10287 SourceLocation CurrentLocation) {
10288 assert(!Class->isDependentContext() && "should not define dependent move");
10289
10290 // Only a virtual base could get implicitly move-assigned multiple times.
10291 // Only a non-trivial move assignment can observe this. We only want to
10292 // diagnose if we implicitly define an assignment operator that assigns
10293 // two base classes, both of which move-assign the same virtual base.
10294 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10295 Class->getNumBases() < 2)
10296 return;
10297
10298 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10299 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10300 VBaseMap VBases;
10301
Aaron Ballman574705e2014-03-13 15:41:46 +000010302 for (auto &BI : Class->bases()) {
10303 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010304 while (!Worklist.empty()) {
10305 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10306 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10307
10308 // If the base has no non-trivial move assignment operators,
10309 // we don't care about moves from it.
10310 if (!Base->hasNonTrivialMoveAssignment())
10311 continue;
10312
10313 // If there's nothing virtual here, skip it.
10314 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10315 continue;
10316
10317 // If we're not actually going to call a move assignment for this base,
10318 // or the selected move assignment is trivial, skip it.
10319 Sema::SpecialMemberOverloadResult *SMOR =
10320 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10321 /*ConstArg*/false, /*VolatileArg*/false,
10322 /*RValueThis*/true, /*ConstThis*/false,
10323 /*VolatileThis*/false);
10324 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10325 !SMOR->getMethod()->isMoveAssignmentOperator())
10326 continue;
10327
10328 if (BaseSpec->isVirtual()) {
10329 // We're going to move-assign this virtual base, and its move
10330 // assignment operator is not trivial. If this can happen for
10331 // multiple distinct direct bases of Class, diagnose it. (If it
10332 // only happens in one base, we'll diagnose it when synthesizing
10333 // that base class's move assignment operator.)
10334 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010335 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010336 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010337 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010338 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10339 << Class << Base;
10340 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10341 << (Base->getCanonicalDecl() ==
10342 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10343 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010344 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010345 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010346 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10347 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010348
10349 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010350 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010351 }
10352 } else {
10353 // Only walk over bases that have defaulted move assignment operators.
10354 // We assume that any user-provided move assignment operator handles
10355 // the multiple-moves-of-vbase case itself somehow.
10356 if (!SMOR->getMethod()->isDefaulted())
10357 continue;
10358
10359 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010360 for (auto &BI : Base->bases())
10361 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010362 }
10363 }
10364 }
10365}
10366
Sebastian Redl22653ba2011-08-30 19:58:05 +000010367void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10368 CXXMethodDecl *MoveAssignOperator) {
10369 assert((MoveAssignOperator->isDefaulted() &&
10370 MoveAssignOperator->isOverloadedOperator() &&
10371 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010372 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10373 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010374 "DefineImplicitMoveAssignment called for wrong function");
10375
10376 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10377
10378 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10379 MoveAssignOperator->setInvalidDecl();
10380 return;
10381 }
10382
Eli Friedman276dd182013-09-05 00:02:25 +000010383 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010384
Eli Friedmaneaf34142012-10-18 20:14:08 +000010385 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010386 DiagnosticErrorTrap Trap(Diags);
10387
10388 // C++0x [class.copy]p28:
10389 // The implicitly-defined or move assignment operator for a non-union class
10390 // X performs memberwise move assignment of its subobjects. The direct base
10391 // classes of X are assigned first, in the order of their declaration in the
10392 // base-specifier-list, and then the immediate non-static data members of X
10393 // are assigned, in the order in which they were declared in the class
10394 // definition.
10395
Richard Smithb2504bd2013-11-04 04:26:14 +000010396 // Issue a warning if our implicit move assignment operator will move
10397 // from a virtual base more than once.
10398 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010399
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010401 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010402
10403 // The parameter for the "other" object, which we are move from.
10404 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10405 QualType OtherRefType = Other->getType()->
10406 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010407 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010408 "Bad argument type of defaulted move assignment");
10409
10410 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010411 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10412 ? MoveAssignOperator->getLocEnd()
10413 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010414
Pavel Labath58934982013-08-30 08:52:28 +000010415 // Builds a reference to the "other" object.
10416 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010417 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010418 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010419
Pavel Labath58934982013-08-30 08:52:28 +000010420 // Builds the "this" pointer.
10421 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010422
Sebastian Redl22653ba2011-08-30 19:58:05 +000010423 // Assign base classes.
10424 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010425 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010426 // C++11 [class.copy]p28:
10427 // It is unspecified whether subobjects representing virtual base classes
10428 // are assigned more than once by the implicitly-defined copy assignment
10429 // operator.
10430 // FIXME: Do not assign to a vbase that will be assigned by some other base
10431 // class. For a move-assignment, this can result in the vbase being moved
10432 // multiple times.
10433
Sebastian Redl22653ba2011-08-30 19:58:05 +000010434 // Form the assignment:
10435 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010436 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010437 if (!BaseType->isRecordType()) {
10438 Invalid = true;
10439 continue;
10440 }
10441
10442 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010443 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010444
10445 // Construct the "from" expression, which is an implicit cast to the
10446 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010447 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010448
10449 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010450 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010451
10452 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010453 CastBuilder To(DerefThis,
10454 Context.getCVRQualifiedType(
10455 BaseType, MoveAssignOperator->getTypeQualifiers()),
10456 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010457
10458 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010459 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010460 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010461 /*CopyingBaseSubobject=*/true,
10462 /*Copying=*/false);
10463 if (Move.isInvalid()) {
10464 Diag(CurrentLocation, diag::note_member_synthesized_at)
10465 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10466 MoveAssignOperator->setInvalidDecl();
10467 return;
10468 }
10469
10470 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010471 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010472 }
10473
Sebastian Redl22653ba2011-08-30 19:58:05 +000010474 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010475 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010476 if (Field->isUnnamedBitfield())
10477 continue;
10478
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010479 if (Field->isInvalidDecl()) {
10480 Invalid = true;
10481 continue;
10482 }
10483
Sebastian Redl22653ba2011-08-30 19:58:05 +000010484 // Check for members of reference type; we can't move those.
10485 if (Field->getType()->isReferenceType()) {
10486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10488 Diag(Field->getLocation(), diag::note_declared_at);
10489 Diag(CurrentLocation, diag::note_member_synthesized_at)
10490 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10491 Invalid = true;
10492 continue;
10493 }
10494
10495 // Check for members of const-qualified, non-class type.
10496 QualType BaseType = Context.getBaseElementType(Field->getType());
10497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10500 Diag(Field->getLocation(), diag::note_declared_at);
10501 Diag(CurrentLocation, diag::note_member_synthesized_at)
10502 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10503 Invalid = true;
10504 continue;
10505 }
10506
10507 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010508 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10509 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010510
10511 QualType FieldType = Field->getType().getNonReferenceType();
10512 if (FieldType->isIncompleteArrayType()) {
10513 assert(ClassDecl->hasFlexibleArrayMember() &&
10514 "Incomplete array type is not valid");
10515 continue;
10516 }
10517
10518 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010519 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10520 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010521 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010522 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010523 MemberBuilder From(MoveOther, OtherRefType,
10524 /*IsArrow=*/false, MemberLookup);
10525 MemberBuilder To(This, getCurrentThisType(),
10526 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010527
Pavel Labath58934982013-08-30 08:52:28 +000010528 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010529 "Member reference with rvalue base must be rvalue except for reference "
10530 "members, which aren't allowed for move assignment.");
10531
Sebastian Redl22653ba2011-08-30 19:58:05 +000010532 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010533 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010534 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010535 /*CopyingBaseSubobject=*/false,
10536 /*Copying=*/false);
10537 if (Move.isInvalid()) {
10538 Diag(CurrentLocation, diag::note_member_synthesized_at)
10539 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10540 MoveAssignOperator->setInvalidDecl();
10541 return;
10542 }
Richard Smith11d19592012-11-12 23:33:00 +000010543
Sebastian Redl22653ba2011-08-30 19:58:05 +000010544 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010545 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010546 }
10547
10548 if (!Invalid) {
10549 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010550 ExprResult ThisObj =
10551 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10552
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010553 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010554 if (Return.isInvalid())
10555 Invalid = true;
10556 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010557 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010558
10559 if (Trap.hasErrorOccurred()) {
10560 Diag(CurrentLocation, diag::note_member_synthesized_at)
10561 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10562 Invalid = true;
10563 }
10564 }
10565 }
10566
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010567 // The exception specification is needed because we are defining the
10568 // function.
10569 ResolveExceptionSpec(CurrentLocation,
10570 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10571
Sebastian Redl22653ba2011-08-30 19:58:05 +000010572 if (Invalid) {
10573 MoveAssignOperator->setInvalidDecl();
10574 return;
10575 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010576
10577 StmtResult Body;
10578 {
10579 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010580 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010581 /*isStmtExpr=*/false);
10582 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10583 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010584 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010585
10586 if (ASTMutationListener *L = getASTMutationListener()) {
10587 L->CompletedImplicitDefinition(MoveAssignOperator);
10588 }
10589}
10590
Richard Smithd3b5c9082012-07-27 04:22:15 +000010591Sema::ImplicitExceptionSpecification
10592Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10593 CXXRecordDecl *ClassDecl = MD->getParent();
10594
10595 ImplicitExceptionSpecification ExceptSpec(*this);
10596 if (ClassDecl->isInvalidDecl())
10597 return ExceptSpec;
10598
10599 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010600 assert(T->getNumParams() >= 1 && "not a copy ctor");
10601 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010602
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010603 // C++ [except.spec]p14:
10604 // An implicitly declared special member function (Clause 12) shall have an
10605 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010606 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010607 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010608 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010609 continue;
10610
Douglas Gregora6d69502010-07-02 23:41:54 +000010611 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010612 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010613 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010614 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010615 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010616 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010617 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010618 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010619 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010620 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010621 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010622 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010623 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010624 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010625 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010626 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10627 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010628 LookupCopyingConstructor(FieldClassDecl,
10629 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010630 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010631 }
10632 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010633
Richard Smithd3b5c9082012-07-27 04:22:15 +000010634 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010635}
10636
10637CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10638 CXXRecordDecl *ClassDecl) {
10639 // C++ [class.copy]p4:
10640 // If the class definition does not explicitly declare a copy
10641 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010642 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010643
Richard Smith8bf22e52012-11-29 01:34:07 +000010644 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10645 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010646 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010647
Alexis Hunt913820d2011-05-13 06:10:58 +000010648 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10649 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010650 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010651 if (Const)
10652 ArgType = ArgType.withConst();
10653 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010654
Richard Smithb5800092012-06-10 05:43:50 +000010655 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10656 CXXCopyConstructor,
10657 Const);
10658
Douglas Gregor54be3392010-07-01 17:57:27 +000010659 DeclarationName Name
10660 = Context.DeclarationNames.getCXXConstructorName(
10661 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010662 SourceLocation ClassLoc = ClassDecl->getLocation();
10663 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010664
10665 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010666 // member of its class.
10667 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010668 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010669 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010670 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010671 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010672 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010673
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010674 if (getLangOpts().CUDA) {
10675 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10676 CopyConstructor,
10677 /* ConstRHS */ Const,
10678 /* Diagnose */ false);
10679 }
10680
Richard Smithd3b5c9082012-07-27 04:22:15 +000010681 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010682 FunctionProtoType::ExtProtoInfo EPI =
10683 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010684 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010685 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010686
Douglas Gregor54be3392010-07-01 17:57:27 +000010687 // Add the parameter to the constructor.
10688 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010689 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010690 /*IdentifierInfo=*/nullptr,
10691 ArgType, /*TInfo=*/nullptr,
10692 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010693 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010694
Richard Smith6b02d462012-12-08 08:32:28 +000010695 CopyConstructor->setTrivial(
10696 ClassDecl->needsOverloadResolutionForCopyConstructor()
10697 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10698 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010699
Richard Smith852265f2012-03-30 20:53:28 +000010700 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010701 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010702
Richard Smith6b02d462012-12-08 08:32:28 +000010703 // Note that we have declared this constructor.
10704 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10705
10706 if (Scope *S = getScopeForContext(ClassDecl))
10707 PushOnScopeChains(CopyConstructor, S, false);
10708 ClassDecl->addDecl(CopyConstructor);
10709
Douglas Gregor54be3392010-07-01 17:57:27 +000010710 return CopyConstructor;
10711}
10712
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010713void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010714 CXXConstructorDecl *CopyConstructor) {
10715 assert((CopyConstructor->isDefaulted() &&
10716 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010717 !CopyConstructor->doesThisDeclarationHaveABody() &&
10718 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010719 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010720
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010721 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010722 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010723
Richard Smithd577fbb2013-06-13 03:23:42 +000010724 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010725 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010726 // deprecated if the class has a user-declared copy assignment operator
10727 // or a user-declared destructor.
10728 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10729 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10730
Eli Friedmaneaf34142012-10-18 20:14:08 +000010731 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010732 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010733
David Blaikie3fc2f912013-01-17 05:26:25 +000010734 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010735 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010736 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010737 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010738 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010739 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010740 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10741 ? CopyConstructor->getLocEnd()
10742 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010743 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010744 CopyConstructor->setBody(
10745 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010746 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010747
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010748 // The exception specification is needed because we are defining the
10749 // function.
10750 ResolveExceptionSpec(CurrentLocation,
10751 CopyConstructor->getType()->castAs<FunctionProtoType>());
10752
Eli Friedman276dd182013-09-05 00:02:25 +000010753 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010754 MarkVTableUsed(CurrentLocation, ClassDecl);
10755
Sebastian Redlab238a72011-04-24 16:28:06 +000010756 if (ASTMutationListener *L = getASTMutationListener()) {
10757 L->CompletedImplicitDefinition(CopyConstructor);
10758 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010759}
10760
Sebastian Redl22653ba2011-08-30 19:58:05 +000010761Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010762Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10763 CXXRecordDecl *ClassDecl = MD->getParent();
10764
Sebastian Redl22653ba2011-08-30 19:58:05 +000010765 // C++ [except.spec]p14:
10766 // An implicitly declared special member function (Clause 12) shall have an
10767 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010768 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010769 if (ClassDecl->isInvalidDecl())
10770 return ExceptSpec;
10771
10772 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010773 for (const auto &B : ClassDecl->bases()) {
10774 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010775 continue;
10776
Aaron Ballman574705e2014-03-13 15:41:46 +000010777 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010778 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010779 CXXConstructorDecl *Constructor =
10780 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010781 // If this is a deleted function, add it anyway. This might be conformant
10782 // with the standard. This might not. I'm not sure. It might not matter.
10783 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010784 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010785 }
10786 }
10787
10788 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010789 for (const auto &B : ClassDecl->vbases()) {
10790 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010791 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010792 CXXConstructorDecl *Constructor =
10793 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010794 // If this is a deleted function, add it anyway. This might be conformant
10795 // with the standard. This might not. I'm not sure. It might not matter.
10796 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010797 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010798 }
10799 }
10800
10801 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010802 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010803 QualType FieldType = Context.getBaseElementType(F->getType());
10804 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10805 CXXConstructorDecl *Constructor =
10806 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010807 // If this is a deleted function, add it anyway. This might be conformant
10808 // with the standard. This might not. I'm not sure. It might not matter.
10809 // In particular, the problem is that this function never gets called. It
10810 // might just be ill-formed because this function attempts to refer to
10811 // a deleted function here.
10812 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010813 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010814 }
10815 }
10816
10817 return ExceptSpec;
10818}
10819
10820CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10821 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010822 assert(ClassDecl->needsImplicitMoveConstructor());
10823
Richard Smith8bf22e52012-11-29 01:34:07 +000010824 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10825 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010826 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010827
Sebastian Redl22653ba2011-08-30 19:58:05 +000010828 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10829 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010830
Richard Smithb5800092012-06-10 05:43:50 +000010831 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10832 CXXMoveConstructor,
10833 false);
10834
Sebastian Redl22653ba2011-08-30 19:58:05 +000010835 DeclarationName Name
10836 = Context.DeclarationNames.getCXXConstructorName(
10837 Context.getCanonicalType(ClassType));
10838 SourceLocation ClassLoc = ClassDecl->getLocation();
10839 DeclarationNameInfo NameInfo(Name, ClassLoc);
10840
Richard Smith99005e62013-05-07 03:19:20 +000010841 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010842 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010843 // member of its class.
10844 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010845 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010846 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010847 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010848 MoveConstructor->setAccess(AS_public);
10849 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010850
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010851 if (getLangOpts().CUDA) {
10852 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10853 MoveConstructor,
10854 /* ConstRHS */ false,
10855 /* Diagnose */ false);
10856 }
10857
Richard Smithd3b5c9082012-07-27 04:22:15 +000010858 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010859 FunctionProtoType::ExtProtoInfo EPI =
10860 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010861 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010862 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010863
Sebastian Redl22653ba2011-08-30 19:58:05 +000010864 // Add the parameter to the constructor.
10865 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10866 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010867 /*IdentifierInfo=*/nullptr,
10868 ArgType, /*TInfo=*/nullptr,
10869 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010870 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010871
Richard Smith6b02d462012-12-08 08:32:28 +000010872 MoveConstructor->setTrivial(
10873 ClassDecl->needsOverloadResolutionForMoveConstructor()
10874 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10875 : ClassDecl->hasTrivialMoveConstructor());
10876
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010877 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010878 ClassDecl->setImplicitMoveConstructorIsDeleted();
10879 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010880 }
10881
10882 // Note that we have declared this constructor.
10883 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10884
10885 if (Scope *S = getScopeForContext(ClassDecl))
10886 PushOnScopeChains(MoveConstructor, S, false);
10887 ClassDecl->addDecl(MoveConstructor);
10888
10889 return MoveConstructor;
10890}
10891
10892void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10893 CXXConstructorDecl *MoveConstructor) {
10894 assert((MoveConstructor->isDefaulted() &&
10895 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010896 !MoveConstructor->doesThisDeclarationHaveABody() &&
10897 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010898 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10899
10900 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10901 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10902
Eli Friedmaneaf34142012-10-18 20:14:08 +000010903 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010904 DiagnosticErrorTrap Trap(Diags);
10905
David Blaikie3fc2f912013-01-17 05:26:25 +000010906 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010907 Trap.hasErrorOccurred()) {
10908 Diag(CurrentLocation, diag::note_member_synthesized_at)
10909 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10910 MoveConstructor->setInvalidDecl();
10911 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010912 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10913 ? MoveConstructor->getLocEnd()
10914 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010915 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010916 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010917 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010918 }
10919
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010920 // The exception specification is needed because we are defining the
10921 // function.
10922 ResolveExceptionSpec(CurrentLocation,
10923 MoveConstructor->getType()->castAs<FunctionProtoType>());
10924
Eli Friedman276dd182013-09-05 00:02:25 +000010925 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010926 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010927
10928 if (ASTMutationListener *L = getASTMutationListener()) {
10929 L->CompletedImplicitDefinition(MoveConstructor);
10930 }
10931}
10932
Douglas Gregor74f7d502012-02-15 19:33:52 +000010933bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010934 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010935}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010936
10937void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010938 SourceLocation CurrentLocation,
10939 CXXConversionDecl *Conv) {
10940 CXXRecordDecl *Lambda = Conv->getParent();
10941 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10942 // If we are defining a specialization of a conversion to function-ptr
10943 // cache the deduced template arguments for this specialization
10944 // so that we can use them to retrieve the corresponding call-operator
10945 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010946 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10947
Faisal Vali571df122013-09-29 08:45:24 +000010948 // Retrieve the corresponding call-operator specialization.
10949 if (Lambda->isGenericLambda()) {
10950 assert(Conv->isFunctionTemplateSpecialization());
10951 FunctionTemplateDecl *CallOpTemplate =
10952 CallOp->getDescribedFunctionTemplate();
10953 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010954 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010955 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010956 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010957 InsertPos);
10958 assert(CallOpSpec &&
10959 "Conversion operator must have a corresponding call operator");
10960 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10961 }
10962 // Mark the call operator referenced (and add to pending instantiations
10963 // if necessary).
10964 // For both the conversion and static-invoker template specializations
10965 // we construct their body's in this function, so no need to add them
10966 // to the PendingInstantiations.
10967 MarkFunctionReferenced(CurrentLocation, CallOp);
10968
Eli Friedmaneaf34142012-10-18 20:14:08 +000010969 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010970 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010971
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010972 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010973 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10974 // ... and get the corresponding specialization for a generic lambda.
10975 if (Lambda->isGenericLambda()) {
10976 assert(DeducedTemplateArgs &&
10977 "Must have deduced template arguments from Conversion Operator");
10978 FunctionTemplateDecl *InvokeTemplate =
10979 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010980 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010981 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010982 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010983 InsertPos);
10984 assert(InvokeSpec &&
10985 "Must have a corresponding static invoker specialization");
10986 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10987 }
10988 // Construct the body of the conversion function { return __invoke; }.
10989 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010990 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010991 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010992 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010993 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10994 Conv->getLocation(),
10995 Conv->getLocation()));
10996
10997 Conv->markUsed(Context);
10998 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010999
Faisal Vali571df122013-09-29 08:45:24 +000011000 // Fill in the __invoke function with a dummy implementation. IR generation
11001 // will fill in the actual details.
11002 Invoker->markUsed(Context);
11003 Invoker->setReferenced();
11004 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11005
Douglas Gregord3b672c2012-02-16 01:06:16 +000011006 if (ASTMutationListener *L = getASTMutationListener()) {
11007 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011008 L->CompletedImplicitDefinition(Invoker);
11009 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011010}
11011
Faisal Vali571df122013-09-29 08:45:24 +000011012
11013
Douglas Gregord3b672c2012-02-16 01:06:16 +000011014void Sema::DefineImplicitLambdaToBlockPointerConversion(
11015 SourceLocation CurrentLocation,
11016 CXXConversionDecl *Conv)
11017{
Faisal Vali850da1a2013-09-29 17:08:32 +000011018 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011019
Eli Friedman276dd182013-09-05 00:02:25 +000011020 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011021
Eli Friedmaneaf34142012-10-18 20:14:08 +000011022 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011023 DiagnosticErrorTrap Trap(Diags);
11024
Douglas Gregored90df32012-02-22 05:02:47 +000011025 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011026 Expr *This = ActOnCXXThis(CurrentLocation).get();
11027 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011028
Eli Friedman98b01ed2012-03-01 04:01:32 +000011029 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11030 Conv->getLocation(),
11031 Conv, DerefThis);
11032
11033 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11034 // behavior. Note that only the general conversion function does this
11035 // (since it's unusable otherwise); in the case where we inline the
11036 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011037 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011038 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11039 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011040 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011041
11042 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011043 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011044 Conv->setInvalidDecl();
11045 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011046 }
Douglas Gregored90df32012-02-22 05:02:47 +000011047
Douglas Gregored90df32012-02-22 05:02:47 +000011048 // Create the return statement that returns the block from the conversion
11049 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011050 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011051 if (Return.isInvalid()) {
11052 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11053 Conv->setInvalidDecl();
11054 return;
11055 }
11056
11057 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011058 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011059 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011060 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011061 Conv->getLocation()));
11062
Douglas Gregored90df32012-02-22 05:02:47 +000011063 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011064 if (ASTMutationListener *L = getASTMutationListener()) {
11065 L->CompletedImplicitDefinition(Conv);
11066 }
11067}
11068
Douglas Gregord2f70072012-03-10 06:53:13 +000011069/// \brief Determine whether the given list arguments contains exactly one
11070/// "real" (non-default) argument.
11071static bool hasOneRealArgument(MultiExprArg Args) {
11072 switch (Args.size()) {
11073 case 0:
11074 return false;
11075
11076 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011077 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011078 return false;
11079
11080 // fall through
11081 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011082 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011083 }
11084
11085 return false;
11086}
11087
John McCalldadc5752010-08-24 06:29:42 +000011088ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011089Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011090 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011091 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011092 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011093 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011094 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011095 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011096 unsigned ConstructKind,
11097 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011098 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011099
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011100 // C++0x [class.copy]p34:
11101 // When certain criteria are met, an implementation is allowed to
11102 // omit the copy/move construction of a class object, even if the
11103 // copy/move constructor and/or destructor for the object have
11104 // side effects. [...]
11105 // - when a temporary class object that has not been bound to a
11106 // reference (12.2) would be copied/moved to a class object
11107 // with the same cv-unqualified type, the copy/move operation
11108 // can be omitted by constructing the temporary object
11109 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011110 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011111 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011112 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011113 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011114 }
Mike Stump11289f42009-09-09 15:08:12 +000011115
11116 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011117 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011118 IsListInitialization,
11119 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011120 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011121}
11122
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011123/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11124/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011125ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011126Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11127 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011128 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011129 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011130 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011131 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011132 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011133 unsigned ConstructKind,
11134 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011135 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011136 return CXXConstructExpr::Create(
11137 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011138 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11139 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011140 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11141 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011142}
11143
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011144ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11145 assert(Field->hasInClassInitializer());
11146
11147 // If we already have the in-class initializer nothing needs to be done.
11148 if (Field->getInClassInitializer())
11149 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11150
11151 // Maybe we haven't instantiated the in-class initializer. Go check the
11152 // pattern FieldDecl to see if it has one.
11153 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11154
11155 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11156 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11157 DeclContext::lookup_result Lookup =
11158 ClassPattern->lookup(Field->getDeclName());
11159 assert(Lookup.size() == 1);
11160 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11161 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11162 getTemplateInstantiationArgs(Field)))
11163 return ExprError();
11164 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11165 }
11166
11167 // DR1351:
11168 // If the brace-or-equal-initializer of a non-static data member
11169 // invokes a defaulted default constructor of its class or of an
11170 // enclosing class in a potentially evaluated subexpression, the
11171 // program is ill-formed.
11172 //
11173 // This resolution is unworkable: the exception specification of the
11174 // default constructor can be needed in an unevaluated context, in
11175 // particular, in the operand of a noexcept-expression, and we can be
11176 // unable to compute an exception specification for an enclosed class.
11177 //
11178 // Any attempt to resolve the exception specification of a defaulted default
11179 // constructor before the initializer is lexically complete will ultimately
11180 // come here at which point we can diagnose it.
11181 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11182 if (OutermostClass == ParentRD) {
11183 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11184 << ParentRD << Field;
11185 } else {
11186 Diag(Field->getLocEnd(),
11187 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11188 << ParentRD << OutermostClass << Field;
11189 }
11190
11191 return ExprError();
11192}
11193
John McCall03c48482010-02-02 09:10:11 +000011194void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011195 if (VD->isInvalidDecl()) return;
11196
John McCall03c48482010-02-02 09:10:11 +000011197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011198 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011199 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011200 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011201
Chandler Carruth86d17d32011-03-27 21:26:48 +000011202 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011203 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011204 CheckDestructorAccess(VD->getLocation(), Destructor,
11205 PDiag(diag::err_access_dtor_var)
11206 << VD->getDeclName()
11207 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011208 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011209
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011210 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011211 if (!VD->hasGlobalStorage()) return;
11212
11213 // Emit warning for non-trivial dtor in global scope (a real global,
11214 // class-static, function-static).
11215 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11216
11217 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011218 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011219 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011220}
11221
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011222/// \brief Given a constructor and the set of arguments provided for the
11223/// constructor, convert the arguments and add any required default arguments
11224/// to form a proper call to this constructor.
11225///
11226/// \returns true if an error occurred, false otherwise.
11227bool
11228Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11229 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011230 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011231 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011232 bool AllowExplicit,
11233 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011234 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11235 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011236 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011237
11238 const FunctionProtoType *Proto
11239 = Constructor->getType()->getAs<FunctionProtoType>();
11240 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011241 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011242
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011243 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011244 if (NumArgs < NumParams)
11245 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011246 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011247 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011248
11249 VariadicCallType CallType =
11250 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011251 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011252 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011253 Proto, 0,
11254 llvm::makeArrayRef(Args, NumArgs),
11255 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011256 CallType, AllowExplicit,
11257 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011258 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011259
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011260 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011261
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011262 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011263 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011264 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011265
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011266 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011267}
11268
Anders Carlssone363c8e2009-12-12 00:32:00 +000011269static inline bool
11270CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11271 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011272 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011273 if (isa<NamespaceDecl>(DC)) {
11274 return SemaRef.Diag(FnDecl->getLocation(),
11275 diag::err_operator_new_delete_declared_in_namespace)
11276 << FnDecl->getDeclName();
11277 }
11278
11279 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011280 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011281 return SemaRef.Diag(FnDecl->getLocation(),
11282 diag::err_operator_new_delete_declared_static)
11283 << FnDecl->getDeclName();
11284 }
11285
Anders Carlsson60659a82009-12-12 02:43:16 +000011286 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011287}
11288
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011289static inline bool
11290CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11291 CanQualType ExpectedResultType,
11292 CanQualType ExpectedFirstParamType,
11293 unsigned DependentParamTypeDiag,
11294 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011295 QualType ResultType =
11296 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011297
11298 // Check that the result type is not dependent.
11299 if (ResultType->isDependentType())
11300 return SemaRef.Diag(FnDecl->getLocation(),
11301 diag::err_operator_new_delete_dependent_result_type)
11302 << FnDecl->getDeclName() << ExpectedResultType;
11303
11304 // Check that the result type is what we expect.
11305 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11306 return SemaRef.Diag(FnDecl->getLocation(),
11307 diag::err_operator_new_delete_invalid_result_type)
11308 << FnDecl->getDeclName() << ExpectedResultType;
11309
11310 // A function template must have at least 2 parameters.
11311 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11312 return SemaRef.Diag(FnDecl->getLocation(),
11313 diag::err_operator_new_delete_template_too_few_parameters)
11314 << FnDecl->getDeclName();
11315
11316 // The function decl must have at least 1 parameter.
11317 if (FnDecl->getNumParams() == 0)
11318 return SemaRef.Diag(FnDecl->getLocation(),
11319 diag::err_operator_new_delete_too_few_parameters)
11320 << FnDecl->getDeclName();
11321
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011322 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011323 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11324 if (FirstParamType->isDependentType())
11325 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11326 << FnDecl->getDeclName() << ExpectedFirstParamType;
11327
11328 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011329 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011330 ExpectedFirstParamType)
11331 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11332 << FnDecl->getDeclName() << ExpectedFirstParamType;
11333
11334 return false;
11335}
11336
Anders Carlsson12308f42009-12-11 23:23:22 +000011337static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011338CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011339 // C++ [basic.stc.dynamic.allocation]p1:
11340 // A program is ill-formed if an allocation function is declared in a
11341 // namespace scope other than global scope or declared static in global
11342 // scope.
11343 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11344 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011345
11346 CanQualType SizeTy =
11347 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11348
11349 // C++ [basic.stc.dynamic.allocation]p1:
11350 // The return type shall be void*. The first parameter shall have type
11351 // std::size_t.
11352 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11353 SizeTy,
11354 diag::err_operator_new_dependent_param_type,
11355 diag::err_operator_new_param_type))
11356 return true;
11357
11358 // C++ [basic.stc.dynamic.allocation]p1:
11359 // The first parameter shall not have an associated default argument.
11360 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011361 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011362 diag::err_operator_new_default_arg)
11363 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11364
11365 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011366}
11367
11368static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011369CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011370 // C++ [basic.stc.dynamic.deallocation]p1:
11371 // A program is ill-formed if deallocation functions are declared in a
11372 // namespace scope other than global scope or declared static in global
11373 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011374 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11375 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011376
11377 // C++ [basic.stc.dynamic.deallocation]p2:
11378 // Each deallocation function shall return void and its first parameter
11379 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011380 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11381 SemaRef.Context.VoidPtrTy,
11382 diag::err_operator_delete_dependent_param_type,
11383 diag::err_operator_delete_param_type))
11384 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011385
Anders Carlsson12308f42009-12-11 23:23:22 +000011386 return false;
11387}
11388
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011389/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11390/// of this overloaded operator is well-formed. If so, returns false;
11391/// otherwise, emits appropriate diagnostics and returns true.
11392bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011393 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011394 "Expected an overloaded operator declaration");
11395
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011396 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11397
Mike Stump11289f42009-09-09 15:08:12 +000011398 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011399 // The allocation and deallocation functions, operator new,
11400 // operator new[], operator delete and operator delete[], are
11401 // described completely in 3.7.3. The attributes and restrictions
11402 // found in the rest of this subclause do not apply to them unless
11403 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011404 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011405 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011406
Anders Carlsson22f443f2009-12-12 00:26:23 +000011407 if (Op == OO_New || Op == OO_Array_New)
11408 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011409
11410 // C++ [over.oper]p6:
11411 // An operator function shall either be a non-static member
11412 // function or be a non-member function and have at least one
11413 // parameter whose type is a class, a reference to a class, an
11414 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011415 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11416 if (MethodDecl->isStatic())
11417 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011418 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011419 } else {
11420 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011421 for (auto Param : FnDecl->params()) {
11422 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011423 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11424 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011425 ClassOrEnumParam = true;
11426 break;
11427 }
11428 }
11429
Douglas Gregord69246b2008-11-17 16:14:12 +000011430 if (!ClassOrEnumParam)
11431 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011432 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011433 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011434 }
11435
11436 // C++ [over.oper]p8:
11437 // An operator function cannot have default arguments (8.3.6),
11438 // except where explicitly stated below.
11439 //
Mike Stump11289f42009-09-09 15:08:12 +000011440 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011441 // (C++ [over.call]p1).
11442 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011443 for (auto Param : FnDecl->params()) {
11444 if (Param->hasDefaultArg())
11445 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011446 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011447 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011448 }
11449 }
11450
Douglas Gregor6cf08062008-11-10 13:38:07 +000011451 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11452 { false, false, false }
11453#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11454 , { Unary, Binary, MemberOnly }
11455#include "clang/Basic/OperatorKinds.def"
11456 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011457
Douglas Gregor6cf08062008-11-10 13:38:07 +000011458 bool CanBeUnaryOperator = OperatorUses[Op][0];
11459 bool CanBeBinaryOperator = OperatorUses[Op][1];
11460 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011461
11462 // C++ [over.oper]p8:
11463 // [...] Operator functions cannot have more or fewer parameters
11464 // than the number required for the corresponding operator, as
11465 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011466 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011467 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011468 if (Op != OO_Call &&
11469 ((NumParams == 1 && !CanBeUnaryOperator) ||
11470 (NumParams == 2 && !CanBeBinaryOperator) ||
11471 (NumParams < 1) || (NumParams > 2))) {
11472 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011473 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011474 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011475 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011476 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011477 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011478 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011479 assert(CanBeBinaryOperator &&
11480 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011481 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011482 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011483
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011484 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011485 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011486 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011487
Douglas Gregord69246b2008-11-17 16:14:12 +000011488 // Overloaded operators other than operator() cannot be variadic.
11489 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011490 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011491 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011492 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011493 }
11494
11495 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011496 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11497 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011498 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011499 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011500 }
11501
11502 // C++ [over.inc]p1:
11503 // The user-defined function called operator++ implements the
11504 // prefix and postfix ++ operator. If this function is a member
11505 // function with no parameters, or a non-member function with one
11506 // parameter of class or enumeration type, it defines the prefix
11507 // increment operator ++ for objects of that type. If the function
11508 // is a member function with one parameter (which shall be of type
11509 // int) or a non-member function with two parameters (the second
11510 // of which shall be of type int), it defines the postfix
11511 // increment operator ++ for objects of that type.
11512 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11513 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011514 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011515
Richard Smith538b52a2014-01-30 22:24:05 +000011516 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11517 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011518 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011519 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011520 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011521 }
11522
Douglas Gregord69246b2008-11-17 16:14:12 +000011523 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011524}
Chris Lattner3b024a32008-12-17 07:09:26 +000011525
Alexis Huntc88db062010-01-13 09:01:02 +000011526/// CheckLiteralOperatorDeclaration - Check whether the declaration
11527/// of this literal operator function is well-formed. If so, returns
11528/// false; otherwise, emits appropriate diagnostics and returns true.
11529bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011530 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011531 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11532 << FnDecl->getDeclName();
11533 return true;
11534 }
11535
Richard Smith72eebee2012-03-04 09:41:16 +000011536 if (FnDecl->isExternC()) {
11537 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11538 return true;
11539 }
11540
Alexis Huntc88db062010-01-13 09:01:02 +000011541 bool Valid = false;
11542
Richard Smithbcc22fc2012-03-09 08:00:36 +000011543 // This might be the definition of a literal operator template.
11544 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11545 // This might be a specialization of a literal operator template.
11546 if (!TpDecl)
11547 TpDecl = FnDecl->getPrimaryTemplate();
11548
Richard Smithb8b41d32013-10-07 19:57:58 +000011549 // template <char...> type operator "" name() and
11550 // template <class T, T...> type operator "" name() are the only valid
11551 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011552 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011553 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011554 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011555 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11556 if (Params->size() == 1) {
11557 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011558 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011559
Alexis Hunt7dd26172010-04-07 23:11:06 +000011560 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011561 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11562 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11563 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011564 } else if (Params->size() == 2) {
11565 TemplateTypeParmDecl *PmType =
11566 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11567 NonTypeTemplateParmDecl *PmArgs =
11568 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11569
11570 // The second template parameter must be a parameter pack with the
11571 // first template parameter as its type.
11572 if (PmType && PmArgs &&
11573 !PmType->isTemplateParameterPack() &&
11574 PmArgs->isTemplateParameterPack()) {
11575 const TemplateTypeParmType *TArgs =
11576 PmArgs->getType()->getAs<TemplateTypeParmType>();
11577 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11578 TArgs->getIndex() == PmType->getIndex()) {
11579 Valid = true;
11580 if (ActiveTemplateInstantiations.empty())
11581 Diag(FnDecl->getLocation(),
11582 diag::ext_string_literal_operator_template);
11583 }
11584 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011585 }
11586 }
Richard Smith72eebee2012-03-04 09:41:16 +000011587 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011588 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011589 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11590
Richard Smith72eebee2012-03-04 09:41:16 +000011591 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011592
Alexis Hunt079a6f72010-04-07 22:57:35 +000011593 // unsigned long long int, long double, and any character type are allowed
11594 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011595 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11596 Context.hasSameType(T, Context.LongDoubleTy) ||
11597 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011598 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011599 Context.hasSameType(T, Context.Char16Ty) ||
11600 Context.hasSameType(T, Context.Char32Ty)) {
11601 if (++Param == FnDecl->param_end())
11602 Valid = true;
11603 goto FinishedParams;
11604 }
11605
Alexis Hunt079a6f72010-04-07 22:57:35 +000011606 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011607 const PointerType *PT = T->getAs<PointerType>();
11608 if (!PT)
11609 goto FinishedParams;
11610 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011611 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011612 goto FinishedParams;
11613 T = T.getUnqualifiedType();
11614
11615 // Move on to the second parameter;
11616 ++Param;
11617
11618 // If there is no second parameter, the first must be a const char *
11619 if (Param == FnDecl->param_end()) {
11620 if (Context.hasSameType(T, Context.CharTy))
11621 Valid = true;
11622 goto FinishedParams;
11623 }
11624
11625 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11626 // are allowed as the first parameter to a two-parameter function
11627 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011628 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011629 Context.hasSameType(T, Context.Char16Ty) ||
11630 Context.hasSameType(T, Context.Char32Ty)))
11631 goto FinishedParams;
11632
11633 // The second and final parameter must be an std::size_t
11634 T = (*Param)->getType().getUnqualifiedType();
11635 if (Context.hasSameType(T, Context.getSizeType()) &&
11636 ++Param == FnDecl->param_end())
11637 Valid = true;
11638 }
11639
11640 // FIXME: This diagnostic is absolutely terrible.
11641FinishedParams:
11642 if (!Valid) {
11643 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11644 << FnDecl->getDeclName();
11645 return true;
11646 }
11647
Richard Smith768cecc2012-03-09 08:16:22 +000011648 // A parameter-declaration-clause containing a default argument is not
11649 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011650 for (auto Param : FnDecl->params()) {
11651 if (Param->hasDefaultArg()) {
11652 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011653 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011654 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011655 break;
11656 }
11657 }
11658
Richard Smith0df56f42012-03-08 02:39:21 +000011659 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011660 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11661 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011662 // C++11 [usrlit.suffix]p1:
11663 // Literal suffix identifiers that do not start with an underscore
11664 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011665 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11666 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011667 }
Richard Smith0df56f42012-03-08 02:39:21 +000011668
Alexis Huntc88db062010-01-13 09:01:02 +000011669 return false;
11670}
11671
Douglas Gregor07665a62009-01-05 19:45:36 +000011672/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11673/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011674/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11675/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011676/// the '{' brace. Otherwise, this linkage specification does not
11677/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011678Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011679 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011680 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011681 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11682 if (!Lit->isAscii()) {
11683 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11684 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011685 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011686 }
11687
11688 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011689 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011690 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011691 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011692 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011693 Language = LinkageSpecDecl::lang_cxx;
11694 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011695 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11696 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011697 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011698 }
Mike Stump11289f42009-09-09 15:08:12 +000011699
Chris Lattner438e5012008-12-17 07:13:27 +000011700 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011701
Richard Smith4ee696d2014-02-17 23:25:27 +000011702 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11703 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011704 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011705 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011706 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011707 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011708}
11709
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011710/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011711/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11712/// valid, it's the position of the closing '}' brace in a linkage
11713/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011714Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011715 Decl *LinkageSpec,
11716 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011717 if (RBraceLoc.isValid()) {
11718 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11719 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011720 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011721 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011722 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011723}
11724
Michael Han84324352013-02-22 17:15:32 +000011725Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11726 AttributeList *AttrList,
11727 SourceLocation SemiLoc) {
11728 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11729 // Attribute declarations appertain to empty declaration so we handle
11730 // them here.
11731 if (AttrList)
11732 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011733
Michael Han84324352013-02-22 17:15:32 +000011734 CurContext->addDecl(ED);
11735 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011736}
11737
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011738/// \brief Perform semantic analysis for the variable declaration that
11739/// occurs within a C++ catch clause, returning the newly-created
11740/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011741VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011742 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011743 SourceLocation StartLoc,
11744 SourceLocation Loc,
11745 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011746 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011747 QualType ExDeclType = TInfo->getType();
11748
Sebastian Redl54c04d42008-12-22 19:15:10 +000011749 // Arrays and functions decay.
11750 if (ExDeclType->isArrayType())
11751 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11752 else if (ExDeclType->isFunctionType())
11753 ExDeclType = Context.getPointerType(ExDeclType);
11754
11755 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11756 // The exception-declaration shall not denote a pointer or reference to an
11757 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011758 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011759 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011760 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011761 Invalid = true;
11762 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011763
Sebastian Redl54c04d42008-12-22 19:15:10 +000011764 QualType BaseType = ExDeclType;
11765 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011766 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011767 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011768 BaseType = Ptr->getPointeeType();
11769 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011770 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011771 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011772 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011773 BaseType = Ref->getPointeeType();
11774 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011775 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011776 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011777 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011778 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011779 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011780
Mike Stump11289f42009-09-09 15:08:12 +000011781 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011782 RequireNonAbstractType(Loc, ExDeclType,
11783 diag::err_abstract_type_in_decl,
11784 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011785 Invalid = true;
11786
John McCall2ca705e2010-07-24 00:37:23 +000011787 // Only the non-fragile NeXT runtime currently supports C++ catches
11788 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011789 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011790 QualType T = ExDeclType;
11791 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11792 T = RT->getPointeeType();
11793
11794 if (T->isObjCObjectType()) {
11795 Diag(Loc, diag::err_objc_object_catch);
11796 Invalid = true;
11797 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011798 // FIXME: should this be a test for macosx-fragile specifically?
11799 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011800 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011801 }
11802 }
11803
Abramo Bagnaradff19302011-03-08 08:55:46 +000011804 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011805 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011806 ExDecl->setExceptionVariable(true);
11807
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011808 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011809 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011810 Invalid = true;
11811
Douglas Gregor750734c2011-07-06 18:14:43 +000011812 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011813 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011814 // Insulate this from anything else we might currently be parsing.
11815 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11816
Douglas Gregor6de584c2010-03-05 23:38:39 +000011817 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011818 // The object declared in an exception-declaration or, if the
11819 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011820 // copy-initialized (8.5) from the exception object. [...]
11821 // The object is destroyed when the handler exits, after the destruction
11822 // of any automatic objects initialized within the handler.
11823 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011824 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011825 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011826 QualType initType = ExDeclType;
11827
11828 InitializedEntity entity =
11829 InitializedEntity::InitializeVariable(ExDecl);
11830 InitializationKind initKind =
11831 InitializationKind::CreateCopy(Loc, SourceLocation());
11832
11833 Expr *opaqueValue =
11834 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011835 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11836 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011837 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011838 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011839 else {
11840 // If the constructor used was non-trivial, set this as the
11841 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011842 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011843 if (!construct->getConstructor()->isTrivial()) {
11844 Expr *init = MaybeCreateExprWithCleanups(construct);
11845 ExDecl->setInit(init);
11846 }
11847
11848 // And make sure it's destructable.
11849 FinalizeVarWithDestructor(ExDecl, recordType);
11850 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011851 }
11852 }
11853
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011854 if (Invalid)
11855 ExDecl->setInvalidDecl();
11856
11857 return ExDecl;
11858}
11859
11860/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11861/// handler.
John McCall48871652010-08-21 09:40:31 +000011862Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011863 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011864 bool Invalid = D.isInvalidType();
11865
11866 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011867 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11868 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011869 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11870 D.getIdentifierLoc());
11871 Invalid = true;
11872 }
11873
Sebastian Redl54c04d42008-12-22 19:15:10 +000011874 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011875 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011876 LookupOrdinaryName,
11877 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011878 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011879 // it contains any previous declaration, except for function parameters in
11880 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011881 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011882 if (isDeclInScope(PrevDecl, CurContext, S)) {
11883 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11884 << D.getIdentifier();
11885 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11886 Invalid = true;
11887 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011888 // Maybe we will complain about the shadowed template parameter.
11889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011890 }
11891
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011892 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011893 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11894 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011895 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011896 }
11897
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011898 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011899 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011900 D.getIdentifierLoc(),
11901 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011902 if (Invalid)
11903 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011904
Sebastian Redl54c04d42008-12-22 19:15:10 +000011905 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011906 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011907 PushOnScopeChains(ExDecl, S);
11908 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011909 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011910
Douglas Gregor758a8692009-06-17 21:51:59 +000011911 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011912 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011913}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011914
Abramo Bagnaraea947882011-03-08 16:41:52 +000011915Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011916 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011917 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011918 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011919 StringLiteral *AssertMessage =
11920 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011921
Richard Smithded9c2e2012-07-11 22:37:56 +000011922 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011923 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011924
11925 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11926 AssertMessage, RParenLoc, false);
11927}
11928
11929Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11930 Expr *AssertExpr,
11931 StringLiteral *AssertMessage,
11932 SourceLocation RParenLoc,
11933 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011934 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011935 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11936 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011937 // In a static_assert-declaration, the constant-expression shall be a
11938 // constant expression that can be contextually converted to bool.
11939 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11940 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011941 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011942
Richard Smith902ca212011-12-14 23:32:26 +000011943 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011944 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011945 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011946 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011947 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011948
Richard Smithded9c2e2012-07-11 22:37:56 +000011949 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011950 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011951 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011952 if (AssertMessage)
11953 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011954 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011955 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011956 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011957 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011958 }
Mike Stump11289f42009-09-09 15:08:12 +000011959
Abramo Bagnaraea947882011-03-08 16:41:52 +000011960 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011961 AssertExpr, AssertMessage, RParenLoc,
11962 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011963
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011964 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011965 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011966}
Sebastian Redlf769df52009-03-24 22:27:57 +000011967
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011968/// \brief Perform semantic analysis of the given friend type declaration.
11969///
11970/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011971FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011972 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011973 TypeSourceInfo *TSInfo) {
11974 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11975
11976 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011977 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011978
Richard Smithc8239732011-10-18 21:39:00 +000011979 // C++03 [class.friend]p2:
11980 // An elaborated-type-specifier shall be used in a friend declaration
11981 // for a class.*
11982 //
11983 // * The class-key of the elaborated-type-specifier is required.
11984 if (!ActiveTemplateInstantiations.empty()) {
11985 // Do not complain about the form of friend template types during
11986 // template instantiation; we will already have complained when the
11987 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011988 } else {
11989 if (!T->isElaboratedTypeSpecifier()) {
11990 // If we evaluated the type to a record type, suggest putting
11991 // a tag in front.
11992 if (const RecordType *RT = T->getAs<RecordType>()) {
11993 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011994
11995 SmallString<16> InsertionText(" ");
11996 InsertionText += RD->getKindName();
11997
Nick Lewycky36722d22013-02-06 05:59:33 +000011998 Diag(TypeRange.getBegin(),
11999 getLangOpts().CPlusPlus11 ?
12000 diag::warn_cxx98_compat_unelaborated_friend_type :
12001 diag::ext_unelaborated_friend_type)
12002 << (unsigned) RD->getTagKind()
12003 << T
12004 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12005 InsertionText);
12006 } else {
12007 Diag(FriendLoc,
12008 getLangOpts().CPlusPlus11 ?
12009 diag::warn_cxx98_compat_nonclass_type_friend :
12010 diag::ext_nonclass_type_friend)
12011 << T
12012 << TypeRange;
12013 }
12014 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012015 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012016 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012017 diag::warn_cxx98_compat_enum_friend :
12018 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012019 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012020 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012021 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012022
Nick Lewycky36722d22013-02-06 05:59:33 +000012023 // C++11 [class.friend]p3:
12024 // A friend declaration that does not declare a function shall have one
12025 // of the following forms:
12026 // friend elaborated-type-specifier ;
12027 // friend simple-type-specifier ;
12028 // friend typename-specifier ;
12029 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12030 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12031 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012032
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012033 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012034 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012035 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012036 return FriendDecl::Create(Context, CurContext,
12037 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12038 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012039}
12040
John McCallace48cd2010-10-19 01:40:49 +000012041/// Handle a friend tag declaration where the scope specifier was
12042/// templated.
12043Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12044 unsigned TagSpec, SourceLocation TagLoc,
12045 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012046 IdentifierInfo *Name,
12047 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012048 AttributeList *Attr,
12049 MultiTemplateParamsArg TempParamLists) {
12050 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12051
12052 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012053 bool Invalid = false;
12054
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012055 if (TemplateParameterList *TemplateParams =
12056 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012057 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012058 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012059 if (TemplateParams->size() > 0) {
12060 // This is a declaration of a class template.
12061 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012062 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012063
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012064 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12065 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012066 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012067 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012068 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012069 } else {
12070 // The "template<>" header is extraneous.
12071 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12072 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12073 isExplicitSpecialization = true;
12074 }
12075 }
12076
Craig Topperc3ec1492014-05-26 06:22:03 +000012077 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012078
John McCallace48cd2010-10-19 01:40:49 +000012079 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012080 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012081 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012082 isAllExplicitSpecializations = false;
12083 break;
12084 }
12085 }
12086
12087 // FIXME: don't ignore attributes.
12088
12089 // If it's explicit specializations all the way down, just forget
12090 // about the template header and build an appropriate non-templated
12091 // friend. TODO: for source fidelity, remember the headers.
12092 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012093 if (SS.isEmpty()) {
12094 bool Owned = false;
12095 bool IsDependent = false;
12096 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012097 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012098 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012099 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012100 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012101 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012102 /*UnderlyingType=*/TypeResult(),
12103 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012104 }
Richard Smith649c7b062014-01-08 00:56:48 +000012105
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012106 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012107 ElaboratedTypeKeyword Keyword
12108 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012109 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012110 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012111 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012112 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012113
12114 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12115 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012116 DependentNameTypeLoc TL =
12117 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012118 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012119 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012120 TL.setNameLoc(NameLoc);
12121 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012122 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012123 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012124 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012125 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012126 }
12127
12128 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012129 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012130 Friend->setAccess(AS_public);
12131 CurContext->addDecl(Friend);
12132 return Friend;
12133 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012134
12135 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12136
12137
John McCallace48cd2010-10-19 01:40:49 +000012138
12139 // Handle the case of a templated-scope friend class. e.g.
12140 // template <class T> class A<T>::B;
12141 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012142 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12143 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012144 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12145 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12146 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012147 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012148 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012149 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012150 TL.setNameLoc(NameLoc);
12151
12152 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012153 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012154 Friend->setAccess(AS_public);
12155 Friend->setUnsupportedFriend(true);
12156 CurContext->addDecl(Friend);
12157 return Friend;
12158}
12159
12160
John McCall11083da2009-09-16 22:47:08 +000012161/// Handle a friend type declaration. This works in tandem with
12162/// ActOnTag.
12163///
12164/// Notes on friend class templates:
12165///
12166/// We generally treat friend class declarations as if they were
12167/// declaring a class. So, for example, the elaborated type specifier
12168/// in a friend declaration is required to obey the restrictions of a
12169/// class-head (i.e. no typedefs in the scope chain), template
12170/// parameters are required to match up with simple template-ids, &c.
12171/// However, unlike when declaring a template specialization, it's
12172/// okay to refer to a template specialization without an empty
12173/// template parameter declaration, e.g.
12174/// friend class A<T>::B<unsigned>;
12175/// We permit this as a special case; if there are any template
12176/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012177/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012178Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012179 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012180 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012181
12182 assert(DS.isFriendSpecified());
12183 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12184
John McCall11083da2009-09-16 22:47:08 +000012185 // Try to convert the decl specifier to a type. This works for
12186 // friend templates because ActOnTag never produces a ClassTemplateDecl
12187 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012188 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012189 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12190 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012191 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012192 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012193
Douglas Gregor6c110f32010-12-16 01:14:37 +000012194 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012195 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012196
John McCall11083da2009-09-16 22:47:08 +000012197 // This is definitely an error in C++98. It's probably meant to
12198 // be forbidden in C++0x, too, but the specification is just
12199 // poorly written.
12200 //
12201 // The problem is with declarations like the following:
12202 // template <T> friend A<T>::foo;
12203 // where deciding whether a class C is a friend or not now hinges
12204 // on whether there exists an instantiation of A that causes
12205 // 'foo' to equal C. There are restrictions on class-heads
12206 // (which we declare (by fiat) elaborated friend declarations to
12207 // be) that makes this tractable.
12208 //
12209 // FIXME: handle "template <> friend class A<T>;", which
12210 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012211 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012212 Diag(Loc, diag::err_tagless_friend_type_template)
12213 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012214 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012215 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012216
John McCallaa74a0c2009-08-28 07:59:38 +000012217 // C++98 [class.friend]p1: A friend of a class is a function
12218 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012219 // This is fixed in DR77, which just barely didn't make the C++03
12220 // deadline. It's also a very silly restriction that seriously
12221 // affects inner classes and which nobody else seems to implement;
12222 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012223 //
12224 // But note that we could warn about it: it's always useless to
12225 // friend one of your own members (it's not, however, worthless to
12226 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012227
John McCall11083da2009-09-16 22:47:08 +000012228 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012229 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012230 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012231 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012232 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012233 TSI,
John McCall11083da2009-09-16 22:47:08 +000012234 DS.getFriendSpecLoc());
12235 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012236 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012237
12238 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012239 return nullptr;
12240
John McCall11083da2009-09-16 22:47:08 +000012241 D->setAccess(AS_public);
12242 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012243
John McCall48871652010-08-21 09:40:31 +000012244 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012245}
12246
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012247NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12248 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012249 const DeclSpec &DS = D.getDeclSpec();
12250
12251 assert(DS.isFriendSpecified());
12252 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12253
12254 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012255 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012256
12257 // C++ [class.friend]p1
12258 // A friend of a class is a function or class....
12259 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012260 // It *doesn't* see through dependent types, which is correct
12261 // according to [temp.arg.type]p3:
12262 // If a declaration acquires a function type through a
12263 // type dependent on a template-parameter and this causes
12264 // a declaration that does not use the syntactic form of a
12265 // function declarator to have a function type, the program
12266 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012267 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012268 Diag(Loc, diag::err_unexpected_friend);
12269
12270 // It might be worthwhile to try to recover by creating an
12271 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012272 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012273 }
12274
12275 // C++ [namespace.memdef]p3
12276 // - If a friend declaration in a non-local class first declares a
12277 // class or function, the friend class or function is a member
12278 // of the innermost enclosing namespace.
12279 // - The name of the friend is not found by simple name lookup
12280 // until a matching declaration is provided in that namespace
12281 // scope (either before or after the class declaration granting
12282 // friendship).
12283 // - If a friend function is called, its name may be found by the
12284 // name lookup that considers functions from namespaces and
12285 // classes associated with the types of the function arguments.
12286 // - When looking for a prior declaration of a class or a function
12287 // declared as a friend, scopes outside the innermost enclosing
12288 // namespace scope are not considered.
12289
John McCallde3fd222010-10-12 23:13:28 +000012290 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012291 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12292 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012293 assert(Name);
12294
Douglas Gregor6c110f32010-12-16 01:14:37 +000012295 // Check for unexpanded parameter packs.
12296 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12297 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12298 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012299 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012300
John McCall07e91c02009-08-06 02:15:43 +000012301 // The context we found the declaration in, or in which we should
12302 // create the declaration.
12303 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012304 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012305 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012306 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012307
Richard Smith114394f2013-08-09 04:35:01 +000012308 // There are five cases here.
12309 // - There's no scope specifier and we're in a local class. Only look
12310 // for functions declared in the immediately-enclosing block scope.
12311 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012312 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012313 if ((SS.isInvalid() || !SS.isSet()) &&
12314 (FunctionContainingLocalClass =
12315 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12316 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012317 // If a friend declaration appears in a local class and the name
12318 // specified is an unqualified name, a prior declaration is
12319 // looked up without considering scopes that are outside the
12320 // innermost enclosing non-class scope. For a friend function
12321 // declaration, if there is no prior declaration, the program is
12322 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012323
12324 // Find the innermost enclosing non-class scope. This is the block
12325 // scope containing the local class definition (or for a nested class,
12326 // the outer local class).
12327 DCScope = S->getFnParent();
12328
12329 // Look up the function name in the scope.
12330 Previous.clear(LookupLocalFriendName);
12331 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12332
12333 if (!Previous.empty()) {
12334 // All possible previous declarations must have the same context:
12335 // either they were declared at block scope or they are members of
12336 // one of the enclosing local classes.
12337 DC = Previous.getRepresentativeDecl()->getDeclContext();
12338 } else {
12339 // This is ill-formed, but provide the context that we would have
12340 // declared the function in, if we were permitted to, for error recovery.
12341 DC = FunctionContainingLocalClass;
12342 }
Richard Smith541b38b2013-09-20 01:15:31 +000012343 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012344
12345 // C++ [class.friend]p6:
12346 // A function can be defined in a friend declaration of a class if and
12347 // only if the class is a non-local class (9.8), the function name is
12348 // unqualified, and the function has namespace scope.
12349 if (D.isFunctionDefinition()) {
12350 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12351 }
12352
12353 // - There's no scope specifier, in which case we just go to the
12354 // appropriate scope and look for a function or function template
12355 // there as appropriate.
12356 } else if (SS.isInvalid() || !SS.isSet()) {
12357 // C++11 [namespace.memdef]p3:
12358 // If the name in a friend declaration is neither qualified nor
12359 // a template-id and the declaration is a function or an
12360 // elaborated-type-specifier, the lookup to determine whether
12361 // the entity has been previously declared shall not consider
12362 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012363 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012364
John McCallf7cfb222010-10-13 05:45:15 +000012365 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012366 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012367
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012368 // Skip class contexts. If someone can cite chapter and verse
12369 // for this behavior, that would be nice --- it's what GCC and
12370 // EDG do, and it seems like a reasonable intent, but the spec
12371 // really only says that checks for unqualified existing
12372 // declarations should stop at the nearest enclosing namespace,
12373 // not that they should only consider the nearest enclosing
12374 // namespace.
12375 while (DC->isRecord())
12376 DC = DC->getParent();
12377
12378 DeclContext *LookupDC = DC;
12379 while (LookupDC->isTransparentContext())
12380 LookupDC = LookupDC->getParent();
12381
12382 while (true) {
12383 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012384
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012385 if (!Previous.empty()) {
12386 DC = LookupDC;
12387 break;
John McCallf4776592010-10-14 22:22:28 +000012388 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012389
12390 if (isTemplateId) {
12391 if (isa<TranslationUnitDecl>(LookupDC)) break;
12392 } else {
12393 if (LookupDC->isFileContext()) break;
12394 }
12395 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012396 }
12397
John McCallccbc0322010-10-13 06:22:15 +000012398 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012399
John McCallde3fd222010-10-12 23:13:28 +000012400 // - There's a non-dependent scope specifier, in which case we
12401 // compute it and do a previous lookup there for a function
12402 // or function template.
12403 } else if (!SS.getScopeRep()->isDependent()) {
12404 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012405 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012406
Craig Topperc3ec1492014-05-26 06:22:03 +000012407 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012408
12409 LookupQualifiedName(Previous, DC);
12410
12411 // Ignore things found implicitly in the wrong scope.
12412 // TODO: better diagnostics for this case. Suggesting the right
12413 // qualified scope would be nice...
12414 LookupResult::Filter F = Previous.makeFilter();
12415 while (F.hasNext()) {
12416 NamedDecl *D = F.next();
12417 if (!DC->InEnclosingNamespaceSetOf(
12418 D->getDeclContext()->getRedeclContext()))
12419 F.erase();
12420 }
12421 F.done();
12422
12423 if (Previous.empty()) {
12424 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012425 Diag(Loc, diag::err_qualified_friend_not_found)
12426 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012427 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012428 }
12429
12430 // C++ [class.friend]p1: A friend of a class is a function or
12431 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012432 if (DC->Equals(CurContext))
12433 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012434 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012435 diag::warn_cxx98_compat_friend_is_member :
12436 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012437
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012438 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012439 // C++ [class.friend]p6:
12440 // A function can be defined in a friend declaration of a class if and
12441 // only if the class is a non-local class (9.8), the function name is
12442 // unqualified, and the function has namespace scope.
12443 SemaDiagnosticBuilder DB
12444 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12445
12446 DB << SS.getScopeRep();
12447 if (DC->isFileContext())
12448 DB << FixItHint::CreateRemoval(SS.getRange());
12449 SS.clear();
12450 }
John McCallde3fd222010-10-12 23:13:28 +000012451
12452 // - There's a scope specifier that does not match any template
12453 // parameter lists, in which case we use some arbitrary context,
12454 // create a method or method template, and wait for instantiation.
12455 // - There's a scope specifier that does match some template
12456 // parameter lists, which we don't handle right now.
12457 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012458 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012459 // C++ [class.friend]p6:
12460 // A function can be defined in a friend declaration of a class if and
12461 // only if the class is a non-local class (9.8), the function name is
12462 // unqualified, and the function has namespace scope.
12463 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12464 << SS.getScopeRep();
12465 }
12466
John McCallde3fd222010-10-12 23:13:28 +000012467 DC = CurContext;
12468 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012469 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012470
John McCallf7cfb222010-10-13 05:45:15 +000012471 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012472 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012473 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12474 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12475 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012476 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012477 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12478 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012479 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012480 }
John McCall07e91c02009-08-06 02:15:43 +000012481 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012482
Douglas Gregordd847ba2011-11-03 16:37:14 +000012483 // FIXME: This is an egregious hack to cope with cases where the scope stack
12484 // does not contain the declaration context, i.e., in an out-of-line
12485 // definition of a class.
12486 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12487 if (!DCScope) {
12488 FakeDCScope.setEntity(DC);
12489 DCScope = &FakeDCScope;
12490 }
Richard Smith114394f2013-08-09 04:35:01 +000012491
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012492 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012493 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012494 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012495 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012496
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012497 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012498
Richard Smith114394f2013-08-09 04:35:01 +000012499 // If we performed typo correction, we might have added a scope specifier
12500 // and changed the decl context.
12501 DC = ND->getDeclContext();
12502
John McCall759e32b2009-08-31 22:39:49 +000012503 // Add the function declaration to the appropriate lookup tables,
12504 // adjusting the redeclarations list as necessary. We don't
12505 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012506 //
John McCall759e32b2009-08-31 22:39:49 +000012507 // Also update the scope-based lookup if the target context's
12508 // lookup context is in lexical scope.
12509 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012510 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012511 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012512 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012513 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012514 }
John McCallaa74a0c2009-08-28 07:59:38 +000012515
12516 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012517 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012518 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012519 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012520 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012521
John McCalla0a96892012-08-10 03:15:35 +000012522 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012523 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012524 } else {
12525 if (DC->isRecord()) CheckFriendAccess(ND);
12526
John McCall2c2eb122010-10-16 06:59:13 +000012527 FunctionDecl *FD;
12528 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12529 FD = FTD->getTemplatedDecl();
12530 else
12531 FD = cast<FunctionDecl>(ND);
12532
David Majnemer502b0ed2013-06-25 23:09:30 +000012533 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12534 // default argument expression, that declaration shall be a definition
12535 // and shall be the only declaration of the function or function
12536 // template in the translation unit.
12537 if (functionDeclHasDefaultArgument(FD)) {
12538 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12539 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12540 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12541 } else if (!D.isFunctionDefinition())
12542 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12543 }
12544
John McCall2c2eb122010-10-16 06:59:13 +000012545 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012546 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12547 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12548 << SS.getScopeRep() << SS.getRange()
12549 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012550 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012551 }
John McCall2c2eb122010-10-16 06:59:13 +000012552 }
John McCallde3fd222010-10-12 23:13:28 +000012553
John McCall48871652010-08-21 09:40:31 +000012554 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012555}
12556
John McCall48871652010-08-21 09:40:31 +000012557void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12558 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012559
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012560 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012561 if (!Fn) {
12562 Diag(DelLoc, diag::err_deleted_non_function);
12563 return;
12564 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012565
Douglas Gregorec9fd132012-01-14 16:38:05 +000012566 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012567 // Don't consider the implicit declaration we generate for explicit
12568 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012569 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12570 Prev->getPreviousDecl()) &&
12571 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012572 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012573 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12574 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12575 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012576 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012577 // If the declaration wasn't the first, we delete the function anyway for
12578 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012579 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012580 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012581
Nico Rieck9de0a572014-05-29 16:51:19 +000012582 // dllimport/dllexport cannot be deleted.
12583 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12584 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12585 Fn->setInvalidDecl();
12586 }
12587
Richard Smithb4d2a152013-04-02 19:38:47 +000012588 if (Fn->isDeleted())
12589 return;
12590
12591 // See if we're deleting a function which is already known to override a
12592 // non-deleted virtual function.
12593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12594 bool IssuedDiagnostic = false;
12595 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12596 E = MD->end_overridden_methods();
12597 I != E; ++I) {
12598 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12599 if (!IssuedDiagnostic) {
12600 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12601 IssuedDiagnostic = true;
12602 }
12603 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12604 }
12605 }
12606 }
12607
Richard Smithb63b6ee2014-01-22 01:43:19 +000012608 // C++11 [basic.start.main]p3:
12609 // A program that defines main as deleted [...] is ill-formed.
12610 if (Fn->isMain())
12611 Diag(DelLoc, diag::err_deleted_main);
12612
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012613 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012614}
Sebastian Redl4c018662009-04-27 21:33:24 +000012615
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012616void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012617 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012618
12619 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012620 if (MD->getParent()->isDependentType()) {
12621 MD->setDefaulted();
12622 MD->setExplicitlyDefaulted();
12623 return;
12624 }
12625
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012626 CXXSpecialMember Member = getSpecialMember(MD);
12627 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012628 if (!MD->isInvalidDecl())
12629 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012630 return;
12631 }
12632
12633 MD->setDefaulted();
12634 MD->setExplicitlyDefaulted();
12635
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012636 // If this definition appears within the record, do the checking when
12637 // the record is complete.
12638 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012639 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012640 // Find the uninstantiated declaration that actually had the '= default'
12641 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012642 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012643
Richard Smith3901dfe2013-03-27 00:22:47 +000012644 // If the method was defaulted on its first declaration, we will have
12645 // already performed the checking in CheckCompletedCXXClass. Such a
12646 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012647 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012648 return;
12649
Richard Smithd3b5c9082012-07-27 04:22:15 +000012650 CheckExplicitlyDefaultedSpecialMember(MD);
12651
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012652 if (MD->isInvalidDecl())
12653 return;
12654
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012655 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012656 case CXXDefaultConstructor:
12657 DefineImplicitDefaultConstructor(DefaultLoc,
12658 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012659 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012660 case CXXCopyConstructor:
12661 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012662 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012663 case CXXCopyAssignment:
12664 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012665 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012666 case CXXDestructor:
12667 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012668 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012669 case CXXMoveConstructor:
12670 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012671 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012672 case CXXMoveAssignment:
12673 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012674 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012675 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012676 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012677 }
12678 } else {
12679 Diag(DefaultLoc, diag::err_default_special_members);
12680 }
12681}
12682
Sebastian Redl4c018662009-04-27 21:33:24 +000012683static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012684 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012685 Stmt *SubStmt = *CI;
12686 if (!SubStmt)
12687 continue;
12688 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012689 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012690 diag::err_return_in_constructor_handler);
12691 if (!isa<Expr>(SubStmt))
12692 SearchForReturnInStmt(Self, SubStmt);
12693 }
12694}
12695
12696void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12697 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12698 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12699 SearchForReturnInStmt(*this, Handler);
12700 }
12701}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012702
David Blaikie68f71a32013-01-18 23:03:15 +000012703bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012704 const CXXMethodDecl *Old) {
12705 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12706 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12707
12708 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12709
12710 // If the calling conventions match, everything is fine
12711 if (NewCC == OldCC)
12712 return false;
12713
Hans Wennborg2545efe2013-12-11 17:42:11 +000012714 // If the calling conventions mismatch because the new function is static,
12715 // suppress the calling convention mismatch error; the error about static
12716 // function override (err_static_overrides_virtual from
12717 // Sema::CheckFunctionDeclaration) is more clear.
12718 if (New->getStorageClass() == SC_Static)
12719 return false;
12720
Reid Kleckner78af0702013-08-27 23:08:25 +000012721 Diag(New->getLocation(),
12722 diag::err_conflicting_overriding_cc_attributes)
12723 << New->getDeclName() << New->getType() << Old->getType();
12724 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12725 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012726}
12727
Mike Stump11289f42009-09-09 15:08:12 +000012728bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012729 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012730 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12731 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012732
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012733 if (Context.hasSameType(NewTy, OldTy) ||
12734 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012735 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012736
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012737 // Check if the return types are covariant
12738 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012739
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012740 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012741 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12742 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012743 NewClassTy = NewPT->getPointeeType();
12744 OldClassTy = OldPT->getPointeeType();
12745 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012746 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12747 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12748 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12749 NewClassTy = NewRT->getPointeeType();
12750 OldClassTy = OldRT->getPointeeType();
12751 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012752 }
12753 }
Mike Stump11289f42009-09-09 15:08:12 +000012754
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012755 // The return types aren't either both pointers or references to a class type.
12756 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012757 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012758 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012759 << New->getDeclName() << NewTy << OldTy
12760 << New->getReturnTypeSourceRange();
12761 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12762 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012763
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012764 return true;
12765 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012766
Anders Carlssone60365b2009-12-31 18:34:24 +000012767 // C++ [class.virtual]p6:
12768 // If the return type of D::f differs from the return type of B::f, the
12769 // class type in the return type of D::f shall be complete at the point of
12770 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012771 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12772 if (!RT->isBeingDefined() &&
12773 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012774 diag::err_covariant_return_incomplete,
12775 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012776 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012777 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012778
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012779 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012780 // Check if the new class derives from the old class.
12781 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012782 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12783 << New->getDeclName() << NewTy << OldTy
12784 << New->getReturnTypeSourceRange();
12785 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12786 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012787 return true;
12788 }
Mike Stump11289f42009-09-09 15:08:12 +000012789
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012790 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012791 if (CheckDerivedToBaseConversion(
12792 NewClassTy, OldClassTy,
12793 diag::err_covariant_return_inaccessible_base,
12794 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12795 New->getLocation(), New->getReturnTypeSourceRange(),
12796 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012797 // FIXME: this note won't trigger for delayed access control
12798 // diagnostics, and it's impossible to get an undelayed error
12799 // here from access control during the original parse because
12800 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012801 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12802 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012803 return true;
12804 }
12805 }
Mike Stump11289f42009-09-09 15:08:12 +000012806
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012807 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012808 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012809 Diag(New->getLocation(),
12810 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012811 << New->getDeclName() << NewTy << OldTy
12812 << New->getReturnTypeSourceRange();
12813 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12814 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012815 return true;
12816 };
Mike Stump11289f42009-09-09 15:08:12 +000012817
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012818
12819 // The new class type must have the same or less qualifiers as the old type.
12820 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12821 Diag(New->getLocation(),
12822 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012823 << New->getDeclName() << NewTy << OldTy
12824 << New->getReturnTypeSourceRange();
12825 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12826 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012827 return true;
12828 };
Mike Stump11289f42009-09-09 15:08:12 +000012829
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012830 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012831}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012832
Douglas Gregor21920e372009-12-01 17:24:26 +000012833/// \brief Mark the given method pure.
12834///
12835/// \param Method the method to be marked pure.
12836///
12837/// \param InitRange the source range that covers the "0" initializer.
12838bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012839 SourceLocation EndLoc = InitRange.getEnd();
12840 if (EndLoc.isValid())
12841 Method->setRangeEnd(EndLoc);
12842
Douglas Gregor21920e372009-12-01 17:24:26 +000012843 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12844 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012845 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012846 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012847
12848 if (!Method->isInvalidDecl())
12849 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12850 << Method->getDeclName() << InitRange;
12851 return true;
12852}
12853
Douglas Gregor926410d2012-02-21 02:22:07 +000012854/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012855static bool isStaticDataMember(const Decl *D) {
12856 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12857 return Var->isStaticDataMember();
12858
12859 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012860}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012861
John McCall1f4ee7b2009-12-19 09:28:58 +000012862/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12863/// an initializer for the out-of-line declaration 'Dcl'. The scope
12864/// is a fresh scope pushed for just this purpose.
12865///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012866/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12867/// static data member of class X, names should be looked up in the scope of
12868/// class X.
John McCall48871652010-08-21 09:40:31 +000012869void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012870 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012871 if (!D || D->isInvalidDecl())
12872 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012873
Richard Smitha2302242013-12-05 07:51:02 +000012874 // We will always have a nested name specifier here, but this declaration
12875 // might not be out of line if the specifier names the current namespace:
12876 // extern int n;
12877 // int ::n = 0;
12878 if (D->isOutOfLine())
12879 EnterDeclaratorContext(S, D->getDeclContext());
12880
Douglas Gregor926410d2012-02-21 02:22:07 +000012881 // If we are parsing the initializer for a static data member, push a
12882 // new expression evaluation context that is associated with this static
12883 // data member.
12884 if (isStaticDataMember(D))
12885 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012886}
12887
12888/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012889/// initializer for the out-of-line declaration 'D'.
12890void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012891 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012892 if (!D || D->isInvalidDecl())
12893 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012894
Douglas Gregor926410d2012-02-21 02:22:07 +000012895 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012896 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012897
Richard Smitha2302242013-12-05 07:51:02 +000012898 if (D->isOutOfLine())
12899 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012900}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012901
12902/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12903/// C++ if/switch/while/for statement.
12904/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012905DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012906 // C++ 6.4p2:
12907 // The declarator shall not specify a function or an array.
12908 // The type-specifier-seq shall not contain typedef and shall not declare a
12909 // new class or enumeration.
12910 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12911 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012912
12913 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012914 if (!Dcl)
12915 return true;
12916
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012917 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12918 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012919 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012920 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012921 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012922
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012923 return Dcl;
12924}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012925
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012926void Sema::LoadExternalVTableUses() {
12927 if (!ExternalSource)
12928 return;
12929
12930 SmallVector<ExternalVTableUse, 4> VTables;
12931 ExternalSource->ReadUsedVTables(VTables);
12932 SmallVector<VTableUse, 4> NewUses;
12933 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12934 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12935 = VTablesUsed.find(VTables[I].Record);
12936 // Even if a definition wasn't required before, it may be required now.
12937 if (Pos != VTablesUsed.end()) {
12938 if (!Pos->second && VTables[I].DefinitionRequired)
12939 Pos->second = true;
12940 continue;
12941 }
12942
12943 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12944 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12945 }
12946
12947 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12948}
12949
Douglas Gregor88d292c2010-05-13 16:44:06 +000012950void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12951 bool DefinitionRequired) {
12952 // Ignore any vtable uses in unevaluated operands or for classes that do
12953 // not have a vtable.
12954 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012955 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012956 return;
12957
Douglas Gregor88d292c2010-05-13 16:44:06 +000012958 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012959 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012960 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12961 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12962 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12963 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012964 // If we already had an entry, check to see if we are promoting this vtable
12965 // to required a definition. If so, we need to reappend to the VTableUses
12966 // list, since we may have already processed the first entry.
12967 if (DefinitionRequired && !Pos.first->second) {
12968 Pos.first->second = true;
12969 } else {
12970 // Otherwise, we can early exit.
12971 return;
12972 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012973 } else {
12974 // The Microsoft ABI requires that we perform the destructor body
12975 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12976 // the deleting destructor is emitted with the vtable, not with the
12977 // destructor definition as in the Itanium ABI.
12978 // If it has a definition, we do the check at that point instead.
12979 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12980 Class->hasUserDeclaredDestructor() &&
12981 !Class->getDestructor()->isDefined() &&
12982 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012983 CXXDestructorDecl *DD = Class->getDestructor();
12984 ContextRAII SavedContext(*this, DD);
12985 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012986 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012987 }
12988
12989 // Local classes need to have their virtual members marked
12990 // immediately. For all other classes, we mark their virtual members
12991 // at the end of the translation unit.
12992 if (Class->isLocalClass())
12993 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012994 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012995 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012996}
12997
Douglas Gregor88d292c2010-05-13 16:44:06 +000012998bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012999 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013000 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013001 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013002
Douglas Gregor88d292c2010-05-13 16:44:06 +000013003 // Note: The VTableUses vector could grow as a result of marking
13004 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013005 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013006 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013007 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013008 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013009 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013010 if (!Class)
13011 continue;
13012
13013 SourceLocation Loc = VTableUses[I].second;
13014
Richard Smithd3b5c9082012-07-27 04:22:15 +000013015 bool DefineVTable = true;
13016
Douglas Gregor88d292c2010-05-13 16:44:06 +000013017 // If this class has a key function, but that key function is
13018 // defined in another translation unit, we don't need to emit the
13019 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013020 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013021 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013022 // The key function is in another translation unit.
13023 DefineVTable = false;
13024 TemplateSpecializationKind TSK =
13025 KeyFunction->getTemplateSpecializationKind();
13026 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13027 TSK != TSK_ImplicitInstantiation &&
13028 "Instantiations don't have key functions");
13029 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013030 } else if (!KeyFunction) {
13031 // If we have a class with no key function that is the subject
13032 // of an explicit instantiation declaration, suppress the
13033 // vtable; it will live with the explicit instantiation
13034 // definition.
13035 bool IsExplicitInstantiationDeclaration
13036 = Class->getTemplateSpecializationKind()
13037 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013038 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013039 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013040 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013041 if (TSK == TSK_ExplicitInstantiationDeclaration)
13042 IsExplicitInstantiationDeclaration = true;
13043 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13044 IsExplicitInstantiationDeclaration = false;
13045 break;
13046 }
13047 }
13048
13049 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013050 DefineVTable = false;
13051 }
13052
13053 // The exception specifications for all virtual members may be needed even
13054 // if we are not providing an authoritative form of the vtable in this TU.
13055 // We may choose to emit it available_externally anyway.
13056 if (!DefineVTable) {
13057 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13058 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013059 }
13060
13061 // Mark all of the virtual members of this class as referenced, so
13062 // that we can build a vtable. Then, tell the AST consumer that a
13063 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013064 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013065 MarkVirtualMembersReferenced(Loc, Class);
13066 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13067 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
13068
13069 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013070 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013071 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013072 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013073 if (!KeyFunction ||
13074 (KeyFunction->hasBody(KeyFunctionDef) &&
13075 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013076 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13077 TSK_ExplicitInstantiationDefinition
13078 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13079 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013080 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013081 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013082 VTableUses.clear();
13083
Douglas Gregor97509692011-04-22 22:25:37 +000013084 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013085}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013086
Richard Smithd3b5c9082012-07-27 04:22:15 +000013087void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13088 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013089 for (const auto *I : RD->methods())
13090 if (I->isVirtual() && !I->isPure())
13091 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013092}
13093
Rafael Espindola5b334082010-03-26 00:36:59 +000013094void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13095 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013096 // Mark all functions which will appear in RD's vtable as used.
13097 CXXFinalOverriderMap FinalOverriders;
13098 RD->getFinalOverriders(FinalOverriders);
13099 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13100 E = FinalOverriders.end();
13101 I != E; ++I) {
13102 for (OverridingMethods::const_iterator OI = I->second.begin(),
13103 OE = I->second.end();
13104 OI != OE; ++OI) {
13105 assert(OI->second.size() > 0 && "no final overrider");
13106 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013107
Richard Smith4ff9ff92012-07-07 06:59:51 +000013108 // C++ [basic.def.odr]p2:
13109 // [...] A virtual member function is used if it is not pure. [...]
13110 if (!Overrider->isPure())
13111 MarkFunctionReferenced(Loc, Overrider);
13112 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013113 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013114
13115 // Only classes that have virtual bases need a VTT.
13116 if (RD->getNumVBases() == 0)
13117 return;
13118
Aaron Ballman574705e2014-03-13 15:41:46 +000013119 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013120 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013121 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013122 if (Base->getNumVBases() == 0)
13123 continue;
13124 MarkVirtualMembersReferenced(Loc, Base);
13125 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013126}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013127
13128/// SetIvarInitializers - This routine builds initialization ASTs for the
13129/// Objective-C implementation whose ivars need be initialized.
13130void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013131 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013132 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013133 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013134 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013135 CollectIvarsToConstructOrDestruct(OID, ivars);
13136 if (ivars.empty())
13137 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013138 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013139 for (unsigned i = 0; i < ivars.size(); i++) {
13140 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013141 if (Field->isInvalidDecl())
13142 continue;
13143
Alexis Hunt1d792652011-01-08 20:30:50 +000013144 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013145 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13146 InitializationKind InitKind =
13147 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013148
13149 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13150 ExprResult MemberInit =
13151 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013152 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013153 // Note, MemberInit could actually come back empty if no initialization
13154 // is required (e.g., because it would call a trivial default constructor)
13155 if (!MemberInit.get() || MemberInit.isInvalid())
13156 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013157
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013158 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013159 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13160 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013161 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013162 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013163 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013164
13165 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013166 if (const RecordType *RecordTy =
13167 Context.getBaseElementType(Field->getType())
13168 ->getAs<RecordType>()) {
13169 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013170 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013171 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013172 CheckDestructorAccess(Field->getLocation(), Destructor,
13173 PDiag(diag::err_access_dtor_ivar)
13174 << Context.getBaseElementType(Field->getType()));
13175 }
13176 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013177 }
13178 ObjCImplementation->setIvarInitializers(Context,
13179 AllToInit.data(), AllToInit.size());
13180 }
13181}
Alexis Hunt6118d662011-05-04 05:57:24 +000013182
Alexis Hunt27a761d2011-05-04 23:29:54 +000013183static
13184void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13185 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13186 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13187 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13188 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013189 if (Ctor->isInvalidDecl())
13190 return;
13191
Richard Smith802c4b72012-08-23 06:16:52 +000013192 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13193
13194 // Target may not be determinable yet, for instance if this is a dependent
13195 // call in an uninstantiated template.
13196 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013197 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013198 (void)Target->hasBody(FNTarget);
13199 Target = const_cast<CXXConstructorDecl*>(
13200 cast_or_null<CXXConstructorDecl>(FNTarget));
13201 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013202
13203 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13204 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013205 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013206
David Blaikie82e95a32014-11-19 07:49:47 +000013207 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013208 return;
13209
13210 // We know that beyond here, we aren't chaining into a cycle.
13211 if (!Target || !Target->isDelegatingConstructor() ||
13212 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013213 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013214 Current.clear();
13215 // We've hit a cycle.
13216 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13217 Current.count(TCanonical)) {
13218 // If we haven't diagnosed this cycle yet, do so now.
13219 if (!Invalid.count(TCanonical)) {
13220 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013221 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013222 << Ctor;
13223
Richard Smith802c4b72012-08-23 06:16:52 +000013224 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013225 if (TCanonical != Canonical)
13226 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13227
13228 CXXConstructorDecl *C = Target;
13229 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013230 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013231 (void)C->getTargetConstructor()->hasBody(FNTarget);
13232 assert(FNTarget && "Ctor cycle through bodiless function");
13233
Richard Smith802c4b72012-08-23 06:16:52 +000013234 C = const_cast<CXXConstructorDecl*>(
13235 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013236 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13237 }
13238 }
13239
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013240 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013241 Current.clear();
13242 } else {
13243 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13244 }
13245}
13246
13247
Alexis Hunt6118d662011-05-04 05:57:24 +000013248void Sema::CheckDelegatingCtorCycles() {
13249 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13250
Douglas Gregorbae31202011-07-27 21:57:17 +000013251 for (DelegatingCtorDeclsType::iterator
13252 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013253 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013254 I != E; ++I)
13255 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013256
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013257 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13258 CE = Invalid.end();
13259 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013260 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013261}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013262
Douglas Gregor3024f072012-04-16 07:05:22 +000013263namespace {
13264 /// \brief AST visitor that finds references to the 'this' expression.
13265 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13266 Sema &S;
13267
13268 public:
13269 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13270
13271 bool VisitCXXThisExpr(CXXThisExpr *E) {
13272 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13273 << E->isImplicit();
13274 return false;
13275 }
13276 };
13277}
13278
13279bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13280 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13281 if (!TSInfo)
13282 return false;
13283
13284 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013285 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013286 if (!ProtoTL)
13287 return false;
13288
13289 // C++11 [expr.prim.general]p3:
13290 // [The expression this] shall not appear before the optional
13291 // cv-qualifier-seq and it shall not appear within the declaration of a
13292 // static member function (although its type and value category are defined
13293 // within a static member function as they are within a non-static member
13294 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013295 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013296 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013297 FindCXXThisExpr Finder(*this);
13298
13299 // If the return type came after the cv-qualifier-seq, check it now.
13300 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013301 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013302 return true;
13303
13304 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013305 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13306 return true;
13307
13308 return checkThisInStaticMemberFunctionAttributes(Method);
13309}
13310
13311bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13312 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13313 if (!TSInfo)
13314 return false;
13315
13316 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013317 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013318 if (!ProtoTL)
13319 return false;
13320
David Blaikie6adc78e2013-02-18 22:06:02 +000013321 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013322 FindCXXThisExpr Finder(*this);
13323
Douglas Gregor3024f072012-04-16 07:05:22 +000013324 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013325 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013326 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013327 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013328 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013329 case EST_DynamicNone:
13330 case EST_MSAny:
13331 case EST_None:
13332 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013333
Douglas Gregor3024f072012-04-16 07:05:22 +000013334 case EST_ComputedNoexcept:
13335 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13336 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013337
Douglas Gregor3024f072012-04-16 07:05:22 +000013338 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013339 for (const auto &E : Proto->exceptions()) {
13340 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013341 return true;
13342 }
13343 break;
13344 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013345
13346 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013347}
13348
13349bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13350 FindCXXThisExpr Finder(*this);
13351
13352 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013353 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013354 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013355 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013356 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013357 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013358 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013359 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013360 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013361 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013362 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013363 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013364 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013365 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013366 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013367 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013368 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013369 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013370 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013371 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013372 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013373 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013374 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013375 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013376 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013377 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013378 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013379 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013380 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013381 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013382 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013383
13384 if (Arg && !Finder.TraverseStmt(Arg))
13385 return true;
13386
13387 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13388 if (!Finder.TraverseStmt(Args[I]))
13389 return true;
13390 }
13391 }
13392
13393 return false;
13394}
13395
Richard Smith2e321552014-11-12 02:00:47 +000013396void Sema::checkExceptionSpecification(
13397 bool IsTopLevel, ExceptionSpecificationType EST,
13398 ArrayRef<ParsedType> DynamicExceptions,
13399 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13400 SmallVectorImpl<QualType> &Exceptions,
13401 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013402 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013403 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013404 if (EST == EST_Dynamic) {
13405 Exceptions.reserve(DynamicExceptions.size());
13406 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13407 // FIXME: Preserve type source info.
13408 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13409
Richard Smith2e321552014-11-12 02:00:47 +000013410 if (IsTopLevel) {
13411 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13412 collectUnexpandedParameterPacks(ET, Unexpanded);
13413 if (!Unexpanded.empty()) {
13414 DiagnoseUnexpandedParameterPacks(
13415 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13416 Unexpanded);
13417 continue;
13418 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013419 }
13420
13421 // Check that the type is valid for an exception spec, and
13422 // drop it if not.
13423 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13424 Exceptions.push_back(ET);
13425 }
Richard Smith8acb4282014-07-31 21:57:55 +000013426 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013427 return;
13428 }
Richard Smith8acb4282014-07-31 21:57:55 +000013429
Douglas Gregor433e0532012-04-16 18:27:27 +000013430 if (EST == EST_ComputedNoexcept) {
13431 // If an error occurred, there's no expression here.
13432 if (NoexceptExpr) {
13433 assert((NoexceptExpr->isTypeDependent() ||
13434 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13435 Context.BoolTy) &&
13436 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013437 if (IsTopLevel && NoexceptExpr &&
13438 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013439 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013440 return;
13441 }
Richard Smith8acb4282014-07-31 21:57:55 +000013442
Douglas Gregor433e0532012-04-16 18:27:27 +000013443 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013444 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013445 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013446 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013447 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013448 }
13449 return;
13450 }
13451}
13452
Richard Smith0b3a4622014-11-13 20:01:57 +000013453void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13454 ExceptionSpecificationType EST,
13455 SourceRange SpecificationRange,
13456 ArrayRef<ParsedType> DynamicExceptions,
13457 ArrayRef<SourceRange> DynamicExceptionRanges,
13458 Expr *NoexceptExpr) {
13459 if (!MethodD)
13460 return;
13461
13462 // Dig out the method we're referring to.
13463 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13464 MethodD = FunTmpl->getTemplatedDecl();
13465
13466 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13467 if (!Method)
13468 return;
13469
13470 // Check the exception specification.
13471 llvm::SmallVector<QualType, 4> Exceptions;
13472 FunctionProtoType::ExceptionSpecInfo ESI;
13473 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13474 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13475 ESI);
13476
13477 // Update the exception specification on the function type.
13478 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13479
13480 if (Method->isStatic())
13481 checkThisInStaticMemberFunctionExceptionSpec(Method);
13482
13483 if (Method->isVirtual()) {
13484 // Check overrides, which we previously had to delay.
13485 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13486 OEnd = Method->end_overridden_methods();
13487 O != OEnd; ++O)
13488 CheckOverridingFunctionExceptionSpec(Method, *O);
13489 }
13490}
13491
John McCall5e77d762013-04-16 07:28:30 +000013492/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13493///
13494MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13495 SourceLocation DeclStart,
13496 Declarator &D, Expr *BitWidth,
13497 InClassInitStyle InitStyle,
13498 AccessSpecifier AS,
13499 AttributeList *MSPropertyAttr) {
13500 IdentifierInfo *II = D.getIdentifier();
13501 if (!II) {
13502 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013503 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013504 }
13505 SourceLocation Loc = D.getIdentifierLoc();
13506
13507 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13508 QualType T = TInfo->getType();
13509 if (getLangOpts().CPlusPlus) {
13510 CheckExtraCXXDefaultArguments(D);
13511
13512 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13513 UPPC_DataMemberType)) {
13514 D.setInvalidType();
13515 T = Context.IntTy;
13516 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13517 }
13518 }
13519
13520 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13521
13522 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13523 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13524 diag::err_invalid_thread)
13525 << DeclSpec::getSpecifierName(TSCS);
13526
13527 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013528 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013529 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13530 LookupName(Previous, S);
13531 switch (Previous.getResultKind()) {
13532 case LookupResult::Found:
13533 case LookupResult::FoundUnresolvedValue:
13534 PrevDecl = Previous.getAsSingle<NamedDecl>();
13535 break;
13536
13537 case LookupResult::FoundOverloaded:
13538 PrevDecl = Previous.getRepresentativeDecl();
13539 break;
13540
13541 case LookupResult::NotFound:
13542 case LookupResult::NotFoundInCurrentInstantiation:
13543 case LookupResult::Ambiguous:
13544 break;
13545 }
13546
13547 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13548 // Maybe we will complain about the shadowed template parameter.
13549 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13550 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013551 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013552 }
13553
13554 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013555 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013556
13557 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013558 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013559 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13560 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013561 ProcessDeclAttributes(TUScope, NewPD, D);
13562 NewPD->setAccess(AS);
13563
13564 if (NewPD->isInvalidDecl())
13565 Record->setInvalidDecl();
13566
13567 if (D.getDeclSpec().isModulePrivateSpecified())
13568 NewPD->setModulePrivate();
13569
13570 if (NewPD->isInvalidDecl() && PrevDecl) {
13571 // Don't introduce NewFD into scope; there's already something
13572 // with the same name in the same scope.
13573 } else if (II) {
13574 PushOnScopeChains(NewPD, S);
13575 } else
13576 Record->addDecl(NewPD);
13577
13578 return NewPD;
13579}