blob: 4a9120be2ffbde943b362c72fe74144adcc28a95 [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
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000015#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000016#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000028#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000029#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000038#include "clang/Sema/SemaInternal.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"
Richard Smith7873de02016-08-11 22:25:46 +000042#include "llvm/ADT/StringExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000043#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000044#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000045
46using namespace clang;
47
Chris Lattner58258242008-04-10 02:22:51 +000048//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
Chris Lattnerb0d38442008-04-12 23:52:44 +000052namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000058 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000059 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 Expr *DefaultArg;
61 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 public:
Mike Stump11289f42009-09-09 15:08:12 +000064 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000066
Chris Lattnerb0d38442008-04-12 23:52:44 +000067 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000069 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000070 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000071 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 };
Chris Lattner58258242008-04-10 02:22:51 +000073
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
Benjamin Kramer642f1732015-07-02 21:03:14 +000077 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000080 }
81
Chris Lattnerb0d38442008-04-12 23:52:44 +000082 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000096 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000098 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000099 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +0000100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000103 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000104 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108
Douglas Gregor8e12c382008-11-04 13:41:56 +0000109 return false;
110 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111
Douglas Gregor97a9c812008-11-04 14:32:21 +0000112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000117 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000120 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000121
John McCall7353c862013-04-09 01:56:28 +0000122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?");
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
Douglas Gregorf0d49512012-02-10 23:30:22 +0000139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getLocStart(),
147 diag::err_lambda_capture_default_arg);
148 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000149}
Chris Lattner58258242008-04-10 02:22:51 +0000150
Richard Smithb7151b92013-04-10 06:11:48 +0000151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
Davide Italiano1a7f6482015-07-16 22:37:54 +0000170 switch(EST) {
171 // If this function can throw any exceptions, make a note of that.
172 case EST_MSAny:
173 case EST_None:
174 ClearExceptions();
175 ComputedEST = EST;
176 return;
177 // FIXME: If the call to this decl is using any of its default arguments, we
178 // need to search them for potentially-throwing calls.
179 // If this function has a basic noexcept, it doesn't affect the outcome.
180 case EST_BasicNoexcept:
181 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000184 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000188 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000189 case EST_ComputedNoexcept:
190 {
Richard Smithf623c962012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000198 // noexcept(false) -> no spec on the new function
199 if (NR == FunctionProtoType::NR_Throw) {
200 ClearExceptions();
201 ComputedEST = EST_None;
202 }
203 // noexcept(true) won't change anything either.
204 return;
205 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000206 default:
207 break;
208 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000318 }
319
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
322 // parameter pack.
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
326 return;
327 }
328
Anders Carlssonf1c26952009-08-25 01:02:06 +0000329 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000332 Param->setInvalidDecl();
333 return;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
John McCallb268a282010-08-23 23:25:46 +0000336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000337}
338
Douglas Gregor58354032008-12-24 00:01:03 +0000339/// ActOnParamUnparsedDefaultArgument - We've seen a default
340/// argument for a function parameter, but we can't parse it yet
341/// because we're inside a class definition. Note that this default
342/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000343void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000346 if (!param)
347 return;
Mike Stump11289f42009-09-09 15:08:12 +0000348
John McCall48871652010-08-21 09:40:31 +0000349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000350 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000351 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000352}
353
Douglas Gregor4d87df52008-12-16 21:30:33 +0000354/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000356void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000358 if (!param)
359 return;
Mike Stump11289f42009-09-09 15:08:12 +0000360
John McCall48871652010-08-21 09:40:31 +0000361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000362 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000363 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000364 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
367 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000368}
369
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000370/// CheckExtraCXXDefaultArguments - Check for any extra default
371/// arguments in the declarator, which is not a function declaration
372/// or definition and therefore is not permitted to have default
373/// arguments. This routine should be invoked for every declarator
374/// that is not a function declaration or definition.
375void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000383 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
390 // arguments.
391 MightBeFunction = false;
392 continue;
393 }
Alp Tokerc5350722014-02-26 22:27:52 +0000394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ++argIdx) {
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000397 if (Param->hasUnparsedDefaultArg()) {
Malcolm Parsonsca9d8342016-11-17 21:00:09 +0000398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
David Majnemerb3c6d522015-01-13 07:42:33 +0000400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000407 << SR;
Douglas Gregor58354032008-12-24 00:01:03 +0000408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000411 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000412 }
413 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000416 }
417 }
418}
419
David Majnemer502b0ed2013-06-25 23:09:30 +0000420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
Craig Toppere4794282012-09-21 04:33:26 +0000431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 bool Invalid = false;
438
Richard Smithc7d48d12015-05-20 17:50:35 +0000439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
Nico Webera6916892016-06-10 18:53:04 +0000474 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
Richard Smithafe4aa82017-02-10 02:19:05 +0000650 // FIXME: It's not clear what should happen if multiple declarations of a
651 // deduction guide have different explicitness. For now at least we simply
652 // reject any case where the explicitness changes.
Richard Smithbc491202017-02-17 20:05:37 +0000653 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
654 if (NewGuide && NewGuide->isExplicitSpecified() !=
655 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
Richard Smithafe4aa82017-02-10 02:19:05 +0000656 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
Richard Smithbc491202017-02-17 20:05:37 +0000657 << NewGuide->isExplicitSpecified();
Richard Smithafe4aa82017-02-10 02:19:05 +0000658 Diag(Old->getLocation(), diag::note_previous_declaration);
659 }
660
David Majnemer502b0ed2013-06-25 23:09:30 +0000661 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000662 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000663 // the only declaration of the function or function template in the
664 // translation unit.
665 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
666 functionDeclHasDefaultArgument(Old)) {
667 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
668 Diag(Old->getLocation(), diag::note_previous_declaration);
669 Invalid = true;
670 }
671
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000672 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000673}
674
Richard Smith7873de02016-08-11 22:25:46 +0000675NamedDecl *
676Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
677 MultiTemplateParamsArg TemplateParamLists) {
678 assert(D.isDecompositionDeclarator());
679 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
680
681 // The syntax only allows a decomposition declarator as a simple-declaration
682 // or a for-range-declaration, but we parse it in more cases than that.
683 if (!D.mayHaveDecompositionDeclarator()) {
684 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
685 << Decomp.getSourceRange();
686 return nullptr;
687 }
688
689 if (!TemplateParamLists.empty()) {
690 // FIXME: There's no rule against this, but there are also no rules that
691 // would actually make it usable, so we reject it for now.
692 Diag(TemplateParamLists.front()->getTemplateLoc(),
693 diag::err_decomp_decl_template);
694 return nullptr;
695 }
696
697 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
698 ? diag::warn_cxx14_compat_decomp_decl
699 : diag::ext_decomp_decl)
700 << Decomp.getSourceRange();
701
702 // The semantic context is always just the current context.
703 DeclContext *const DC = CurContext;
704
705 // C++1z [dcl.dcl]/8:
706 // The decl-specifier-seq shall contain only the type-specifier auto
707 // and cv-qualifiers.
708 auto &DS = D.getDeclSpec();
709 {
710 SmallVector<StringRef, 8> BadSpecifiers;
711 SmallVector<SourceLocation, 8> BadSpecifierLocs;
712 if (auto SCS = DS.getStorageClassSpec()) {
713 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
714 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
715 }
716 if (auto TSCS = DS.getThreadStorageClassSpec()) {
717 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
718 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
719 }
720 if (DS.isConstexprSpecified()) {
721 BadSpecifiers.push_back("constexpr");
722 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
723 }
724 if (DS.isInlineSpecified()) {
725 BadSpecifiers.push_back("inline");
726 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
727 }
728 if (!BadSpecifiers.empty()) {
729 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
730 Err << (int)BadSpecifiers.size()
731 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
732 // Don't add FixItHints to remove the specifiers; we do still respect
733 // them when building the underlying variable.
734 for (auto Loc : BadSpecifierLocs)
735 Err << SourceRange(Loc, Loc);
736 }
737 // We can't recover from it being declared as a typedef.
738 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
739 return nullptr;
740 }
741
742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
743 QualType R = TInfo->getType();
744
745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
746 UPPC_DeclarationType))
747 D.setInvalidType();
748
749 // The syntax only allows a single ref-qualifier prior to the decomposition
750 // declarator. No other declarator chunks are permitted. Also check the type
751 // specifier here.
752 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
753 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
754 (D.getNumTypeObjects() == 1 &&
755 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
756 Diag(Decomp.getLSquareLoc(),
757 (D.hasGroupingParens() ||
758 (D.getNumTypeObjects() &&
759 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
760 ? diag::err_decomp_decl_parens
761 : diag::err_decomp_decl_type)
762 << R;
763
764 // In most cases, there's no actual problem with an explicitly-specified
765 // type, but a function type won't work here, and ActOnVariableDeclarator
766 // shouldn't be called for such a type.
767 if (R->isFunctionType())
768 D.setInvalidType();
769 }
770
771 // Build the BindingDecls.
772 SmallVector<BindingDecl*, 8> Bindings;
773
774 // Build the BindingDecls.
775 for (auto &B : D.getDecompositionDeclarator().bindings()) {
776 // Check for name conflicts.
777 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
778 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
779 ForRedeclaration);
780 LookupName(Previous, S,
781 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
782
783 // It's not permitted to shadow a template parameter name.
784 if (Previous.isSingleResult() &&
785 Previous.getFoundDecl()->isTemplateParameter()) {
786 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
787 Previous.getFoundDecl());
788 Previous.clear();
789 }
790
791 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
792 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
793 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
794 /*AllowInlineNamespace*/false);
795 if (!Previous.empty()) {
796 auto *Old = Previous.getRepresentativeDecl();
797 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
798 Diag(Old->getLocation(), diag::note_previous_definition);
799 }
800
Richard Smith32cb8c92016-08-12 00:53:41 +0000801 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000802 PushOnScopeChains(BD, S, true);
803 Bindings.push_back(BD);
804 ParsingInitForAutoVars.insert(BD);
805 }
806
807 // There are no prior lookup results for the variable itself, because it
808 // is unnamed.
809 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
810 Decomp.getLSquareLoc());
811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
812
813 // Build the variable that holds the non-decomposed object.
814 bool AddToScope = true;
815 NamedDecl *New =
816 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
817 MultiTemplateParamsArg(), AddToScope, Bindings);
818 CurContext->addHiddenDecl(New);
819
820 if (isInOpenMPDeclareTargetContext())
821 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
822
823 return New;
824}
825
826static bool checkSimpleDecomposition(
827 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000828 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000829 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
830 if ((int64_t)Bindings.size() != NumElems) {
831 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
832 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
833 << (NumElems < Bindings.size());
834 return true;
835 }
836
837 unsigned I = 0;
838 for (auto *B : Bindings) {
839 SourceLocation Loc = B->getLocation();
840 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
841 if (E.isInvalid())
842 return true;
843 E = GetInit(Loc, E.get(), I++);
844 if (E.isInvalid())
845 return true;
846 B->setBinding(ElemType, E.get());
847 }
848
849 return false;
850}
851
852static bool checkArrayLikeDecomposition(Sema &S,
853 ArrayRef<BindingDecl *> Bindings,
854 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000855 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000856 QualType ElemType) {
857 return checkSimpleDecomposition(
858 S, Bindings, Src, DecompType, NumElems, ElemType,
859 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
860 ExprResult E = S.ActOnIntegerConstant(Loc, I);
861 if (E.isInvalid())
862 return ExprError();
863 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
864 });
865}
866
867static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
868 ValueDecl *Src, QualType DecompType,
869 const ConstantArrayType *CAT) {
870 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
871 llvm::APSInt(CAT->getSize()),
872 CAT->getElementType());
873}
874
875static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
876 ValueDecl *Src, QualType DecompType,
877 const VectorType *VT) {
878 return checkArrayLikeDecomposition(
879 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
880 S.Context.getQualifiedType(VT->getElementType(),
881 DecompType.getQualifiers()));
882}
883
884static bool checkComplexDecomposition(Sema &S,
885 ArrayRef<BindingDecl *> Bindings,
886 ValueDecl *Src, QualType DecompType,
887 const ComplexType *CT) {
888 return checkSimpleDecomposition(
889 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
890 S.Context.getQualifiedType(CT->getElementType(),
891 DecompType.getQualifiers()),
892 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
893 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
894 });
895}
896
897static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
898 TemplateArgumentListInfo &Args) {
899 SmallString<128> SS;
900 llvm::raw_svector_ostream OS(SS);
901 bool First = true;
902 for (auto &Arg : Args.arguments()) {
903 if (!First)
904 OS << ", ";
905 Arg.getArgument().print(PrintingPolicy, OS);
906 First = false;
907 }
908 return OS.str();
909}
910
911static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
912 SourceLocation Loc, StringRef Trait,
913 TemplateArgumentListInfo &Args,
914 unsigned DiagID) {
915 auto DiagnoseMissing = [&] {
916 if (DiagID)
917 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
918 Args);
919 return true;
920 };
921
922 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
923 NamespaceDecl *Std = S.getStdNamespace();
924 if (!Std)
925 return DiagnoseMissing();
926
927 // Look up the trait itself, within namespace std. We can diagnose various
928 // problems with this lookup even if we've been asked to not diagnose a
929 // missing specialization, because this can only fail if the user has been
930 // declaring their own names in namespace std or we don't support the
931 // standard library implementation in use.
932 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
933 Loc, Sema::LookupOrdinaryName);
934 if (!S.LookupQualifiedName(Result, Std))
935 return DiagnoseMissing();
936 if (Result.isAmbiguous())
937 return true;
938
939 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
940 if (!TraitTD) {
941 Result.suppressDiagnostics();
942 NamedDecl *Found = *Result.begin();
943 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
944 S.Diag(Found->getLocation(), diag::note_declared_at);
945 return true;
946 }
947
948 // Build the template-id.
949 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
950 if (TraitTy.isNull())
951 return true;
952 if (!S.isCompleteType(Loc, TraitTy)) {
953 if (DiagID)
954 S.RequireCompleteType(
955 Loc, TraitTy, DiagID,
956 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
957 return true;
958 }
959
960 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
961 assert(RD && "specialization of class template is not a class?");
962
963 // Look up the member of the trait type.
964 S.LookupQualifiedName(TraitMemberLookup, RD);
965 return TraitMemberLookup.isAmbiguous();
966}
967
968static TemplateArgumentLoc
969getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
970 uint64_t I) {
971 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
972 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
973}
974
975static TemplateArgumentLoc
976getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
977 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
978}
979
980namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
981
982static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
983 llvm::APSInt &Size) {
984 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
985
986 DeclarationName Value = S.PP.getIdentifierInfo("value");
987 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
988
989 // Form template argument list for tuple_size<T>.
990 TemplateArgumentListInfo Args(Loc, Loc);
991 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
992
993 // If there's no tuple_size specialization, it's not tuple-like.
994 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
995 return IsTupleLike::NotTupleLike;
996
Richard Smith208732e2016-12-08 03:24:55 +0000997 // If we get this far, we've committed to the tuple interpretation, but
998 // we can still fail if there actually isn't a usable ::value.
Richard Smith7873de02016-08-11 22:25:46 +0000999
1000 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1001 LookupResult &R;
1002 TemplateArgumentListInfo &Args;
1003 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1004 : R(R), Args(Args) {}
1005 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1006 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1007 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1008 }
1009 } Diagnoser(R, Args);
1010
1011 if (R.empty()) {
1012 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1013 return IsTupleLike::Error;
1014 }
1015
1016 ExprResult E =
1017 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1018 if (E.isInvalid())
1019 return IsTupleLike::Error;
1020
1021 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1022 if (E.isInvalid())
1023 return IsTupleLike::Error;
1024
1025 return IsTupleLike::TupleLike;
1026}
1027
1028/// \return std::tuple_element<I, T>::type.
1029static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1030 unsigned I, QualType T) {
1031 // Form template argument list for tuple_element<I, T>.
1032 TemplateArgumentListInfo Args(Loc, Loc);
1033 Args.addArgument(
1034 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1035 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1036
1037 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1038 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1039 if (lookupStdTypeTraitMember(
1040 S, R, Loc, "tuple_element", Args,
1041 diag::err_decomp_decl_std_tuple_element_not_specialized))
1042 return QualType();
1043
1044 auto *TD = R.getAsSingle<TypeDecl>();
1045 if (!TD) {
1046 R.suppressDiagnostics();
1047 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1048 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1049 if (!R.empty())
1050 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1051 return QualType();
1052 }
1053
1054 return S.Context.getTypeDeclType(TD);
1055}
1056
1057namespace {
1058struct BindingDiagnosticTrap {
1059 Sema &S;
1060 DiagnosticErrorTrap Trap;
1061 BindingDecl *BD;
1062
1063 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1064 : S(S), Trap(S.Diags), BD(BD) {}
1065 ~BindingDiagnosticTrap() {
1066 if (Trap.hasErrorOccurred())
1067 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1068 }
1069};
1070}
1071
Richard Smith3997b1b2016-08-12 01:55:21 +00001072static bool checkTupleLikeDecomposition(Sema &S,
1073 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001074 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001075 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001076 if ((int64_t)Bindings.size() != TupleSize) {
1077 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1078 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1079 << (TupleSize < Bindings.size());
1080 return true;
1081 }
1082
1083 if (Bindings.empty())
1084 return false;
1085
1086 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1087
1088 // [dcl.decomp]p3:
1089 // The unqualified-id get is looked up in the scope of E by class member
1090 // access lookup
1091 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1092 bool UseMemberGet = false;
1093 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1094 if (auto *RD = DecompType->getAsCXXRecordDecl())
1095 S.LookupQualifiedName(MemberGet, RD);
1096 if (MemberGet.isAmbiguous())
1097 return true;
1098 UseMemberGet = !MemberGet.empty();
1099 S.FilterAcceptableTemplateNames(MemberGet);
1100 }
1101
1102 unsigned I = 0;
1103 for (auto *B : Bindings) {
1104 BindingDiagnosticTrap Trap(S, B);
1105 SourceLocation Loc = B->getLocation();
1106
1107 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1108 if (E.isInvalid())
1109 return true;
1110
1111 // e is an lvalue if the type of the entity is an lvalue reference and
1112 // an xvalue otherwise
1113 if (!Src->getType()->isLValueReferenceType())
1114 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1115 E.get(), nullptr, VK_XValue);
1116
1117 TemplateArgumentListInfo Args(Loc, Loc);
1118 Args.addArgument(
1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1120
1121 if (UseMemberGet) {
1122 // if [lookup of member get] finds at least one declaration, the
1123 // initializer is e.get<i-1>().
1124 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1125 CXXScopeSpec(), SourceLocation(), nullptr,
1126 MemberGet, &Args, nullptr);
1127 if (E.isInvalid())
1128 return true;
1129
1130 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1131 } else {
1132 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1133 // in the associated namespaces.
1134 Expr *Get = UnresolvedLookupExpr::Create(
1135 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1136 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1137 UnresolvedSetIterator(), UnresolvedSetIterator());
1138
1139 Expr *Arg = E.get();
1140 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1141 }
1142 if (E.isInvalid())
1143 return true;
1144 Expr *Init = E.get();
1145
1146 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1147 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1148 if (T.isNull())
1149 return true;
1150
1151 // each vi is a variable of type "reference to T" initialized with the
1152 // initializer, where the reference is an lvalue reference if the
1153 // initializer is an lvalue and an rvalue reference otherwise
1154 QualType RefType =
1155 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1156 if (RefType.isNull())
1157 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001158 auto *RefVD = VarDecl::Create(
1159 S.Context, Src->getDeclContext(), Loc, Loc,
1160 B->getDeclName().getAsIdentifierInfo(), RefType,
1161 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1162 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1163 RefVD->setTSCSpec(Src->getTSCSpec());
1164 RefVD->setImplicit();
1165 if (Src->isInlineSpecified())
1166 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001167 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001168
Richard Smith97fcf4b2016-08-14 23:15:52 +00001169 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001170 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1171 InitializationSequence Seq(S, Entity, Kind, Init);
1172 E = Seq.Perform(S, Entity, Kind, Init);
1173 if (E.isInvalid())
1174 return true;
Richard Smithda383632016-08-15 01:33:41 +00001175 E = S.ActOnFinishFullExpr(E.get(), Loc);
1176 if (E.isInvalid())
1177 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001178 RefVD->setInit(E.get());
1179 RefVD->checkInitIsICE();
1180
Richard Smith97fcf4b2016-08-14 23:15:52 +00001181 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1182 DeclarationNameInfo(B->getDeclName(), Loc),
1183 RefVD);
1184 if (E.isInvalid())
1185 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001186
1187 B->setBinding(T, E.get());
1188 I++;
1189 }
1190
1191 return false;
1192}
1193
1194/// Find the base class to decompose in a built-in decomposition of a class type.
1195/// This base class search is, unfortunately, not quite like any other that we
1196/// perform anywhere else in C++.
1197static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1198 SourceLocation Loc,
1199 const CXXRecordDecl *RD,
1200 CXXCastPath &BasePath) {
1201 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1202 CXXBasePath &Path) {
1203 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1204 };
1205
1206 const CXXRecordDecl *ClassWithFields = nullptr;
1207 if (RD->hasDirectFields())
1208 // [dcl.decomp]p4:
1209 // Otherwise, all of E's non-static data members shall be public direct
1210 // members of E ...
1211 ClassWithFields = RD;
1212 else {
1213 // ... or of ...
1214 CXXBasePaths Paths;
1215 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1216 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1217 // If no classes have fields, just decompose RD itself. (This will work
1218 // if and only if zero bindings were provided.)
1219 return RD;
1220 }
1221
1222 CXXBasePath *BestPath = nullptr;
1223 for (auto &P : Paths) {
1224 if (!BestPath)
1225 BestPath = &P;
1226 else if (!S.Context.hasSameType(P.back().Base->getType(),
1227 BestPath->back().Base->getType())) {
1228 // ... the same ...
1229 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1230 << false << RD << BestPath->back().Base->getType()
1231 << P.back().Base->getType();
1232 return nullptr;
1233 } else if (P.Access < BestPath->Access) {
1234 BestPath = &P;
1235 }
1236 }
1237
1238 // ... unambiguous ...
1239 QualType BaseType = BestPath->back().Base->getType();
1240 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1241 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1242 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1243 return nullptr;
1244 }
1245
1246 // ... public base class of E.
1247 if (BestPath->Access != AS_public) {
1248 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1249 << RD << BaseType;
1250 for (auto &BS : *BestPath) {
1251 if (BS.Base->getAccessSpecifier() != AS_public) {
1252 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1253 << (BS.Base->getAccessSpecifier() == AS_protected)
1254 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1255 break;
1256 }
1257 }
1258 return nullptr;
1259 }
1260
1261 ClassWithFields = BaseType->getAsCXXRecordDecl();
1262 S.BuildBasePathArray(Paths, BasePath);
1263 }
1264
1265 // The above search did not check whether the selected class itself has base
1266 // classes with fields, so check that now.
1267 CXXBasePaths Paths;
1268 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1269 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1270 << (ClassWithFields == RD) << RD << ClassWithFields
1271 << Paths.front().back().Base->getType();
1272 return nullptr;
1273 }
1274
1275 return ClassWithFields;
1276}
1277
1278static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1279 ValueDecl *Src, QualType DecompType,
1280 const CXXRecordDecl *RD) {
1281 CXXCastPath BasePath;
1282 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1283 if (!RD)
1284 return true;
1285 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1286 DecompType.getQualifiers());
1287
1288 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001289 unsigned NumFields =
1290 std::count_if(RD->field_begin(), RD->field_end(),
1291 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001292 assert(Bindings.size() != NumFields);
1293 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1294 << DecompType << (unsigned)Bindings.size() << NumFields
1295 << (NumFields < Bindings.size());
1296 return true;
1297 };
1298
1299 // all of E's non-static data members shall be public [...] members,
1300 // E shall not have an anonymous union member, ...
1301 unsigned I = 0;
1302 for (auto *FD : RD->fields()) {
1303 if (FD->isUnnamedBitfield())
1304 continue;
1305
1306 if (FD->isAnonymousStructOrUnion()) {
1307 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1308 << DecompType << FD->getType()->isUnionType();
1309 S.Diag(FD->getLocation(), diag::note_declared_at);
1310 return true;
1311 }
1312
1313 // We have a real field to bind.
1314 if (I >= Bindings.size())
1315 return DiagnoseBadNumberOfBindings();
1316 auto *B = Bindings[I++];
1317
1318 SourceLocation Loc = B->getLocation();
1319 if (FD->getAccess() != AS_public) {
1320 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1321
1322 // Determine whether the access specifier was explicit.
1323 bool Implicit = true;
1324 for (const auto *D : RD->decls()) {
1325 if (declaresSameEntity(D, FD))
1326 break;
1327 if (isa<AccessSpecDecl>(D)) {
1328 Implicit = false;
1329 break;
1330 }
1331 }
1332
1333 S.Diag(FD->getLocation(), diag::note_access_natural)
1334 << (FD->getAccess() == AS_protected) << Implicit;
1335 return true;
1336 }
1337
1338 // Initialize the binding to Src.FD.
1339 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1343 VK_LValue, &BasePath);
1344 if (E.isInvalid())
1345 return true;
1346 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1347 CXXScopeSpec(), FD,
1348 DeclAccessPair::make(FD, FD->getAccess()),
1349 DeclarationNameInfo(FD->getDeclName(), Loc));
1350 if (E.isInvalid())
1351 return true;
1352
1353 // If the type of the member is T, the referenced type is cv T, where cv is
1354 // the cv-qualification of the decomposition expression.
1355 //
1356 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1357 // 'const' to the type of the field.
1358 Qualifiers Q = DecompType.getQualifiers();
1359 if (FD->isMutable())
1360 Q.removeConst();
1361 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1362 }
1363
1364 if (I != Bindings.size())
1365 return DiagnoseBadNumberOfBindings();
1366
1367 return false;
1368}
1369
Richard Smith3997b1b2016-08-12 01:55:21 +00001370void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001371 QualType DecompType = DD->getType();
1372
1373 // If the type of the decomposition is dependent, then so is the type of
1374 // each binding.
1375 if (DecompType->isDependentType()) {
1376 for (auto *B : DD->bindings())
1377 B->setType(Context.DependentTy);
1378 return;
1379 }
1380
1381 DecompType = DecompType.getNonReferenceType();
1382 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1383
1384 // C++1z [dcl.decomp]/2:
1385 // If E is an array type [...]
1386 // As an extension, we also support decomposition of built-in complex and
1387 // vector types.
1388 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1389 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1390 DD->setInvalidDecl();
1391 return;
1392 }
1393 if (auto *VT = DecompType->getAs<VectorType>()) {
1394 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1395 DD->setInvalidDecl();
1396 return;
1397 }
1398 if (auto *CT = DecompType->getAs<ComplexType>()) {
1399 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1400 DD->setInvalidDecl();
1401 return;
1402 }
1403
1404 // C++1z [dcl.decomp]/3:
1405 // if the expression std::tuple_size<E>::value is a well-formed integral
1406 // constant expression, [...]
1407 llvm::APSInt TupleSize(32);
1408 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1409 case IsTupleLike::Error:
1410 DD->setInvalidDecl();
1411 return;
1412
1413 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001414 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001415 DD->setInvalidDecl();
1416 return;
1417
1418 case IsTupleLike::NotTupleLike:
1419 break;
1420 }
1421
1422 // C++1z [dcl.dcl]/8:
1423 // [E shall be of array or non-union class type]
1424 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1425 if (!RD || RD->isUnion()) {
1426 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1427 << DD << !RD << DecompType;
1428 DD->setInvalidDecl();
1429 return;
1430 }
1431
1432 // C++1z [dcl.decomp]/4:
1433 // all of E's non-static data members shall be [...] direct members of
1434 // E or of the same unambiguous public base class of E, ...
1435 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1436 DD->setInvalidDecl();
1437}
1438
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001439/// \brief Merge the exception specifications of two variable declarations.
1440///
1441/// This is called when there's a redeclaration of a VarDecl. The function
1442/// checks if the redeclaration might have an exception specification and
1443/// validates compatibility and merges the specs if necessary.
1444void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1445 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001446 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001447 return;
1448
1449 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1450 "Should only be called if types are otherwise the same.");
1451
1452 QualType NewType = New->getType();
1453 QualType OldType = Old->getType();
1454
1455 // We're only interested in pointers and references to functions, as well
1456 // as pointers to member functions.
1457 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1458 NewType = R->getPointeeType();
1459 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1460 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1461 NewType = P->getPointeeType();
1462 OldType = OldType->getAs<PointerType>()->getPointeeType();
1463 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1464 NewType = M->getPointeeType();
1465 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1466 }
1467
1468 if (!NewType->isFunctionProtoType())
1469 return;
1470
1471 // There's lots of special cases for functions. For function pointers, system
1472 // libraries are hopefully not as broken so that we don't need these
1473 // workarounds.
1474 if (CheckEquivalentExceptionSpec(
1475 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1476 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1477 New->setInvalidDecl();
1478 }
1479}
1480
Chris Lattner199abbc2008-04-08 05:04:30 +00001481/// CheckCXXDefaultArguments - Verify that the default arguments for a
1482/// function declaration are well-formed according to C++
1483/// [dcl.fct.default].
1484void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1485 unsigned NumParams = FD->getNumParams();
1486 unsigned p;
1487
1488 // Find first parameter with a default argument
1489 for (p = 0; p < NumParams; ++p) {
1490 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001491 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001492 break;
1493 }
1494
Benjamin Kramerfe257592015-03-27 13:58:41 +00001495 // C++11 [dcl.fct.default]p4:
1496 // In a given function declaration, each parameter subsequent to a parameter
1497 // with a default argument shall have a default argument supplied in this or
1498 // a previous declaration or shall be a function parameter pack. A default
1499 // argument shall not be redefined by a later declaration (not even to the
1500 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001501 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001502 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001503 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001504 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001505 if (Param->isInvalidDecl())
1506 /* We already complained about this parameter. */;
1507 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001508 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001509 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001510 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001511 else
Mike Stump11289f42009-09-09 15:08:12 +00001512 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001513 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Chris Lattner199abbc2008-04-08 05:04:30 +00001515 LastMissingDefaultArg = p;
1516 }
1517 }
1518
1519 if (LastMissingDefaultArg > 0) {
1520 // Some default arguments were missing. Clear out all of the
1521 // default arguments up to (and including) the last missing
1522 // default argument, so that we leave the function parameters
1523 // in a semantically valid state.
1524 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1525 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001526 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001527 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001528 }
1529 }
1530 }
1531}
Douglas Gregor556877c2008-04-13 21:30:24 +00001532
Richard Smitheb3c10c2011-10-01 02:31:28 +00001533// CheckConstexprParameterTypes - Check whether a function's parameter types
1534// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001535// diagnostic and return false.
1536static bool CheckConstexprParameterTypes(Sema &SemaRef,
1537 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001538 unsigned ArgIndex = 0;
1539 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001540 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1541 e = FT->param_type_end();
1542 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001543 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1544 SourceLocation ParamLoc = PD->getLocation();
1545 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001546 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001547 diag::err_constexpr_non_literal_param,
1548 ArgIndex+1, PD->getSourceRange(),
1549 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001550 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001551 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001552 return true;
1553}
1554
1555/// \brief Get diagnostic %select index for tag kind for
1556/// record diagnostic message.
1557/// WARNING: Indexes apply to particular diagnostics only!
1558///
1559/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001560static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001561 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001562 case TTK_Struct: return 0;
1563 case TTK_Interface: return 1;
1564 case TTK_Class: return 2;
1565 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001566 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001567}
1568
1569// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1570// the requirements of a constexpr function definition or a constexpr
1571// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001572// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001573//
Richard Smith3607ffe2012-02-13 03:54:03 +00001574// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1575bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001576 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1577 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001578 // C++11 [dcl.constexpr]p4:
1579 // The definition of a constexpr constructor shall satisfy the following
1580 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001581 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001582 const CXXRecordDecl *RD = MD->getParent();
1583 if (RD->getNumVBases()) {
1584 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1585 << isa<CXXConstructorDecl>(NewFD)
1586 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001587 for (const auto &I : RD->vbases())
1588 Diag(I.getLocStart(),
1589 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001590 return false;
1591 }
Richard Smith7971b692012-01-13 04:54:00 +00001592 }
1593
1594 if (!isa<CXXConstructorDecl>(NewFD)) {
1595 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001596 // The definition of a constexpr function shall satisfy the following
1597 // constraints:
1598 // - it shall not be virtual;
1599 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1600 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001601 Method = Method->getCanonicalDecl();
1602 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001603
Richard Smith3607ffe2012-02-13 03:54:03 +00001604 // If it's not obvious why this function is virtual, find an overridden
1605 // function which uses the 'virtual' keyword.
1606 const CXXMethodDecl *WrittenVirtual = Method;
1607 while (!WrittenVirtual->isVirtualAsWritten())
1608 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1609 if (WrittenVirtual != Method)
1610 Diag(WrittenVirtual->getLocation(),
1611 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001612 return false;
1613 }
1614
1615 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001616 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001617 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001618 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001619 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001620 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001621 }
1622
Richard Smith7971b692012-01-13 04:54:00 +00001623 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001624 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001625 return false;
1626
Richard Smitheb3c10c2011-10-01 02:31:28 +00001627 return true;
1628}
1629
1630/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001631/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001632///
Richard Smithd9f663b2013-04-22 15:31:51 +00001633/// \return true if the body is OK (maybe only as an extension), false if we
1634/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001635static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001636 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1637 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001638 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1639 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001640 for (const auto *DclIt : DS->decls()) {
1641 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001642 case Decl::StaticAssert:
1643 case Decl::Using:
1644 case Decl::UsingShadow:
1645 case Decl::UsingDirective:
1646 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001647 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001648 // - static_assert-declarations
1649 // - using-declarations,
1650 // - using-directives,
1651 continue;
1652
1653 case Decl::Typedef:
1654 case Decl::TypeAlias: {
1655 // - typedef declarations and alias-declarations that do not define
1656 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001657 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001658 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1659 // Don't allow variably-modified types in constexpr functions.
1660 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1661 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1662 << TL.getSourceRange() << TL.getType()
1663 << isa<CXXConstructorDecl>(Dcl);
1664 return false;
1665 }
1666 continue;
1667 }
1668
1669 case Decl::Enum:
1670 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001671 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001672 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001673 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001674 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001675 ? diag::warn_cxx11_compat_constexpr_type_definition
1676 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001677 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001678 continue;
1679
Richard Smithd9f663b2013-04-22 15:31:51 +00001680 case Decl::EnumConstant:
1681 case Decl::IndirectField:
1682 case Decl::ParmVar:
1683 // These can only appear with other declarations which are banned in
1684 // C++11 and permitted in C++1y, so ignore them.
1685 continue;
1686
Richard Smithdca60b42016-08-12 00:39:32 +00001687 case Decl::Var:
1688 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001689 // C++1y [dcl.constexpr]p3 allows anything except:
1690 // a definition of a variable of non-literal type or of static or
1691 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001692 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001693 if (VD->isThisDeclarationADefinition()) {
1694 if (VD->isStaticLocal()) {
1695 SemaRef.Diag(VD->getLocation(),
1696 diag::err_constexpr_local_var_static)
1697 << isa<CXXConstructorDecl>(Dcl)
1698 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1699 return false;
1700 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001701 if (!VD->getType()->isDependentType() &&
1702 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001703 VD->getLocation(), VD->getType(),
1704 diag::err_constexpr_local_var_non_literal_type,
1705 isa<CXXConstructorDecl>(Dcl)))
1706 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001707 if (!VD->getType()->isDependentType() &&
1708 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001709 SemaRef.Diag(VD->getLocation(),
1710 diag::err_constexpr_local_var_no_init)
1711 << isa<CXXConstructorDecl>(Dcl);
1712 return false;
1713 }
1714 }
1715 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001716 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001717 ? diag::warn_cxx11_compat_constexpr_local_var
1718 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001719 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001720 continue;
1721 }
1722
1723 case Decl::NamespaceAlias:
1724 case Decl::Function:
1725 // These are disallowed in C++11 and permitted in C++1y. Allow them
1726 // everywhere as an extension.
1727 if (!Cxx1yLoc.isValid())
1728 Cxx1yLoc = DS->getLocStart();
1729 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001730
1731 default:
1732 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1733 << isa<CXXConstructorDecl>(Dcl);
1734 return false;
1735 }
1736 }
1737
1738 return true;
1739}
1740
1741/// Check that the given field is initialized within a constexpr constructor.
1742///
1743/// \param Dcl The constexpr constructor being checked.
1744/// \param Field The field being checked. This may be a member of an anonymous
1745/// struct or union nested within the class being checked.
1746/// \param Inits All declarations, including anonymous struct/union members and
1747/// indirect members, for which any initialization was provided.
1748/// \param Diagnosed Set to true if an error is produced.
1749static void CheckConstexprCtorInitializer(Sema &SemaRef,
1750 const FunctionDecl *Dcl,
1751 FieldDecl *Field,
1752 llvm::SmallSet<Decl*, 16> &Inits,
1753 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001754 if (Field->isInvalidDecl())
1755 return;
1756
Douglas Gregor556e5862011-10-10 17:22:13 +00001757 if (Field->isUnnamedBitfield())
1758 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001759
Richard Smithab44d5b2013-12-10 08:25:00 +00001760 // Anonymous unions with no variant members and empty anonymous structs do not
1761 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1762 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001763 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001764 (Field->getType()->isUnionType()
1765 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1766 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001767 return;
1768
Richard Smitheb3c10c2011-10-01 02:31:28 +00001769 if (!Inits.count(Field)) {
1770 if (!Diagnosed) {
1771 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1772 Diagnosed = true;
1773 }
1774 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1775 } else if (Field->isAnonymousStructOrUnion()) {
1776 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001777 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001778 // If an anonymous union contains an anonymous struct of which any member
1779 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001780 if (!RD->isUnion() || Inits.count(I))
1781 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001782 }
1783}
1784
Richard Smithd9f663b2013-04-22 15:31:51 +00001785/// Check the provided statement is allowed in a constexpr function
1786/// definition.
1787static bool
1788CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001789 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001790 SourceLocation &Cxx1yLoc) {
1791 // - its function-body shall be [...] a compound-statement that contains only
1792 switch (S->getStmtClass()) {
1793 case Stmt::NullStmtClass:
1794 // - null statements,
1795 return true;
1796
1797 case Stmt::DeclStmtClass:
1798 // - static_assert-declarations
1799 // - using-declarations,
1800 // - using-directives,
1801 // - typedef declarations and alias-declarations that do not define
1802 // classes or enumerations,
1803 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1804 return false;
1805 return true;
1806
1807 case Stmt::ReturnStmtClass:
1808 // - and exactly one return statement;
1809 if (isa<CXXConstructorDecl>(Dcl)) {
1810 // C++1y allows return statements in constexpr constructors.
1811 if (!Cxx1yLoc.isValid())
1812 Cxx1yLoc = S->getLocStart();
1813 return true;
1814 }
1815
1816 ReturnStmts.push_back(S->getLocStart());
1817 return true;
1818
1819 case Stmt::CompoundStmtClass: {
1820 // C++1y allows compound-statements.
1821 if (!Cxx1yLoc.isValid())
1822 Cxx1yLoc = S->getLocStart();
1823
1824 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001825 for (auto *BodyIt : CompStmt->body()) {
1826 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001827 Cxx1yLoc))
1828 return false;
1829 }
1830 return true;
1831 }
1832
1833 case Stmt::AttributedStmtClass:
1834 if (!Cxx1yLoc.isValid())
1835 Cxx1yLoc = S->getLocStart();
1836 return true;
1837
1838 case Stmt::IfStmtClass: {
1839 // C++1y allows if-statements.
1840 if (!Cxx1yLoc.isValid())
1841 Cxx1yLoc = S->getLocStart();
1842
1843 IfStmt *If = cast<IfStmt>(S);
1844 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1845 Cxx1yLoc))
1846 return false;
1847 if (If->getElse() &&
1848 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1849 Cxx1yLoc))
1850 return false;
1851 return true;
1852 }
1853
1854 case Stmt::WhileStmtClass:
1855 case Stmt::DoStmtClass:
1856 case Stmt::ForStmtClass:
1857 case Stmt::CXXForRangeStmtClass:
1858 case Stmt::ContinueStmtClass:
1859 // C++1y allows all of these. We don't allow them as extensions in C++11,
1860 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001861 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001862 break;
1863 if (!Cxx1yLoc.isValid())
1864 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001865 for (Stmt *SubStmt : S->children())
1866 if (SubStmt &&
1867 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001868 Cxx1yLoc))
1869 return false;
1870 return true;
1871
1872 case Stmt::SwitchStmtClass:
1873 case Stmt::CaseStmtClass:
1874 case Stmt::DefaultStmtClass:
1875 case Stmt::BreakStmtClass:
1876 // C++1y allows switch-statements, and since they don't need variable
1877 // mutation, we can reasonably allow them in C++11 as an extension.
1878 if (!Cxx1yLoc.isValid())
1879 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001880 for (Stmt *SubStmt : S->children())
1881 if (SubStmt &&
1882 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001883 Cxx1yLoc))
1884 return false;
1885 return true;
1886
1887 default:
1888 if (!isa<Expr>(S))
1889 break;
1890
1891 // C++1y allows expression-statements.
1892 if (!Cxx1yLoc.isValid())
1893 Cxx1yLoc = S->getLocStart();
1894 return true;
1895 }
1896
1897 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1898 << isa<CXXConstructorDecl>(Dcl);
1899 return false;
1900}
1901
Richard Smitheb3c10c2011-10-01 02:31:28 +00001902/// Check the body for the given constexpr function declaration only contains
1903/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1904///
1905/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001906bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001907 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001908 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001909 // The definition of a constexpr function shall satisfy the following
1910 // constraints: [...]
1911 // - its function-body shall be = delete, = default, or a
1912 // compound-statement
1913 //
Richard Smith74388b42012-02-04 00:33:54 +00001914 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001915 // In the definition of a constexpr constructor, [...]
1916 // - its function-body shall not be a function-try-block;
1917 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1918 << isa<CXXConstructorDecl>(Dcl);
1919 return false;
1920 }
1921
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001922 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001923
1924 // - its function-body shall be [...] a compound-statement that contains only
1925 // [... list of cases ...]
1926 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1927 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001928 for (auto *BodyIt : CompBody->body()) {
1929 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001930 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001931 }
1932
Richard Smithd9f663b2013-04-22 15:31:51 +00001933 if (Cxx1yLoc.isValid())
1934 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001935 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001936 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1937 : diag::ext_constexpr_body_invalid_stmt)
1938 << isa<CXXConstructorDecl>(Dcl);
1939
Richard Smitheb3c10c2011-10-01 02:31:28 +00001940 if (const CXXConstructorDecl *Constructor
1941 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1942 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001943 // DR1359:
1944 // - every non-variant non-static data member and base class sub-object
1945 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001946 // DR1460:
1947 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001948 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001949 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001950 if (Constructor->getNumCtorInitializers() == 0 &&
1951 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001952 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1953 return false;
1954 }
Richard Smithf368fb42011-10-10 16:38:04 +00001955 } else if (!Constructor->isDependentContext() &&
1956 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001957 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1958
1959 // Skip detailed checking if we have enough initializers, and we would
1960 // allow at most one initializer per member.
1961 bool AnyAnonStructUnionMembers = false;
1962 unsigned Fields = 0;
1963 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1964 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001965 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001966 AnyAnonStructUnionMembers = true;
1967 break;
1968 }
1969 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001970 // DR1460:
1971 // - if the class is a union-like class, but is not a union, for each of
1972 // its anonymous union members having variant members, exactly one of
1973 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001974 if (AnyAnonStructUnionMembers ||
1975 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1976 // Check initialization of non-static data members. Base classes are
1977 // always initialized so do not need to be checked. Dependent bases
1978 // might not have initializers in the member initializer list.
1979 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001980 for (const auto *I: Constructor->inits()) {
1981 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001982 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001983 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001984 Inits.insert(ID->chain_begin(), ID->chain_end());
1985 }
1986
1987 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001988 for (auto *I : RD->fields())
1989 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001990 if (Diagnosed)
1991 return false;
1992 }
1993 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001994 } else {
1995 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001996 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001997 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001998 // otherwise if there's no return statement, the function cannot
1999 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002000 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00002001 (Dcl->getReturnType()->isVoidType() ||
2002 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00002003 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00002004 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2005 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00002006 if (!OK)
2007 return false;
2008 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002009 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002010 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002011 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2012 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002013 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2014 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002015 }
2016 }
2017
Richard Smith74388b42012-02-04 00:33:54 +00002018 // C++11 [dcl.constexpr]p5:
2019 // if no function argument values exist such that the function invocation
2020 // substitution would produce a constant expression, the program is
2021 // ill-formed; no diagnostic required.
2022 // C++11 [dcl.constexpr]p3:
2023 // - every constructor call and implicit conversion used in initializing the
2024 // return value shall be one of those allowed in a constant expression.
2025 // C++11 [dcl.constexpr]p4:
2026 // - every constructor involved in initializing non-static data members and
2027 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002028 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002029 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002030 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002031 << isa<CXXConstructorDecl>(Dcl);
2032 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2033 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002034 // Don't return false here: we allow this for compatibility in
2035 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002036 }
2037
Richard Smitheb3c10c2011-10-01 02:31:28 +00002038 return true;
2039}
2040
Douglas Gregor61956c42008-10-31 09:07:45 +00002041/// isCurrentClassName - Determine whether the identifier II is the
2042/// name of the class type currently being defined. In the case of
2043/// nested classes, this will only return true if II is the name of
2044/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002045bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2046 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002047 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002048
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002049 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002050 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002051 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002052 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2053 } else
2054 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2055
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002056 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002057 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002058 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002059}
2060
Richard Smithfb8b7b92013-10-15 00:00:26 +00002061/// \brief Determine whether the identifier II is a typo for the name of
2062/// the class type currently being defined. If so, update it to the identifier
2063/// that should have been used.
2064bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2065 assert(getLangOpts().CPlusPlus && "No class names in C!");
2066
2067 if (!getLangOpts().SpellChecking)
2068 return false;
2069
2070 CXXRecordDecl *CurDecl;
2071 if (SS && SS->isSet() && !SS->isInvalid()) {
2072 DeclContext *DC = computeDeclContext(*SS, true);
2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2074 } else
2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2076
2077 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2078 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2079 < II->getLength()) {
2080 II = CurDecl->getIdentifier();
2081 return true;
2082 }
2083
2084 return false;
2085}
2086
Douglas Gregordc974572012-11-10 07:24:09 +00002087/// \brief Determine whether the given class is a base class of the given
2088/// class, including looking at dependent bases.
2089static bool findCircularInheritance(const CXXRecordDecl *Class,
2090 const CXXRecordDecl *Current) {
2091 SmallVector<const CXXRecordDecl*, 8> Queue;
2092
2093 Class = Class->getCanonicalDecl();
2094 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002095 for (const auto &I : Current->bases()) {
2096 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002097 if (!Base)
2098 continue;
2099
2100 Base = Base->getDefinition();
2101 if (!Base)
2102 continue;
2103
2104 if (Base->getCanonicalDecl() == Class)
2105 return true;
2106
2107 Queue.push_back(Base);
2108 }
2109
2110 if (Queue.empty())
2111 return false;
2112
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002113 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002114 }
2115
2116 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002117}
2118
Mike Stump11289f42009-09-09 15:08:12 +00002119/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002120///
2121/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2122/// and returns NULL otherwise.
2123CXXBaseSpecifier *
2124Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2125 SourceRange SpecifierRange,
2126 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002127 TypeSourceInfo *TInfo,
2128 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002129 QualType BaseType = TInfo->getType();
2130
Douglas Gregor463421d2009-03-03 04:44:36 +00002131 // C++ [class.union]p1:
2132 // A union shall not have base classes.
2133 if (Class->isUnion()) {
2134 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2135 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002136 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002137 }
2138
Douglas Gregor752a5952011-01-03 22:36:02 +00002139 if (EllipsisLoc.isValid() &&
2140 !TInfo->getType()->containsUnexpandedParameterPack()) {
2141 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2142 << TInfo->getTypeLoc().getSourceRange();
2143 EllipsisLoc = SourceLocation();
2144 }
Douglas Gregor62004702012-11-10 01:18:17 +00002145
2146 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2147
2148 if (BaseType->isDependentType()) {
2149 // Make sure that we don't have circular inheritance among our dependent
2150 // bases. For non-dependent bases, the check for completeness below handles
2151 // this.
2152 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2153 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2154 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002155 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002156 Diag(BaseLoc, diag::err_circular_inheritance)
2157 << BaseType << Context.getTypeDeclType(Class);
2158
2159 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2160 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2161 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002162
2163 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002164 }
2165 }
2166
Mike Stump11289f42009-09-09 15:08:12 +00002167 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002168 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002169 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002170 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002171
2172 // Base specifiers must be record types.
2173 if (!BaseType->isRecordType()) {
2174 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002175 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002176 }
2177
2178 // C++ [class.union]p1:
2179 // A union shall not be used as a base class.
2180 if (BaseType->isUnionType()) {
2181 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002182 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002183 }
2184
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002185 // For the MS ABI, propagate DLL attributes to base class templates.
2186 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2187 if (Attr *ClassAttr = getDLLAttr(Class)) {
2188 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2189 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002190 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2191 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002192 }
2193 }
2194 }
2195
Douglas Gregor463421d2009-03-03 04:44:36 +00002196 // C++ [class.derived]p2:
2197 // The class-name in a base-specifier shall not be an incompletely
2198 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002199 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002200 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002201 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002202 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002203 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002204
Eli Friedmanc96d4962009-08-15 21:55:26 +00002205 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002206 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002207 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002208 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002209 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002210 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002211 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002212
David Majnemer9b1754d2013-11-02 12:00:36 +00002213 // A class which contains a flexible array member is not suitable for use as a
2214 // base class:
2215 // - If the layout determines that a base comes before another base,
2216 // the flexible array member would index into the subsequent base.
2217 // - If the layout determines that base comes before the derived class,
2218 // the flexible array member would index into the derived class.
2219 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2220 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2221 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002222 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002223 }
2224
Anders Carlsson65c76d32011-03-25 14:55:14 +00002225 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002226 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002227 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002228 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002229 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002230 << CXXBaseDecl->getDeclName()
2231 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002232 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2233 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002234 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002235 }
2236
John McCall3696dcb2010-08-17 07:23:57 +00002237 if (BaseDecl->isInvalidDecl())
2238 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002239
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002240 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002241 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002242 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002243 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002244}
2245
Douglas Gregor556877c2008-04-13 21:30:24 +00002246/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2247/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002248/// example:
2249/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002250/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002251BaseResult
John McCall48871652010-08-21 09:40:31 +00002252Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002253 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002254 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002255 ParsedType basetype, SourceLocation BaseLoc,
2256 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002257 if (!classdecl)
2258 return true;
2259
Douglas Gregorc40290e2009-03-09 23:48:35 +00002260 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002261 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002262 if (!Class)
2263 return true;
2264
David Majnemer5ef4fe72014-06-13 06:43:46 +00002265 // We haven't yet attached the base specifiers.
2266 Class->setIsParsingBaseSpecifiers();
2267
Richard Smith4c96e992013-02-19 23:47:15 +00002268 // We do not support any C++11 attributes on base-specifiers yet.
2269 // Diagnose any attributes we see.
2270 if (!Attributes.empty()) {
2271 for (AttributeList *Attr = Attributes.getList(); Attr;
2272 Attr = Attr->getNext()) {
2273 if (Attr->isInvalid() ||
2274 Attr->getKind() == AttributeList::IgnoredAttribute)
2275 continue;
2276 Diag(Attr->getLoc(),
2277 Attr->getKind() == AttributeList::UnknownAttribute
2278 ? diag::warn_unknown_attribute_ignored
2279 : diag::err_base_specifier_attribute)
2280 << Attr->getName();
2281 }
2282 }
2283
Craig Topperc3ec1492014-05-26 06:22:03 +00002284 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002285 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002286
Douglas Gregor752a5952011-01-03 22:36:02 +00002287 if (EllipsisLoc.isInvalid() &&
2288 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002289 UPPC_BaseType))
2290 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002291
Douglas Gregor463421d2009-03-03 04:44:36 +00002292 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002293 Virtual, Access, TInfo,
2294 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002295 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002296 else
2297 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002298
Douglas Gregor463421d2009-03-03 04:44:36 +00002299 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002300}
Douglas Gregor556877c2008-04-13 21:30:24 +00002301
Nathan Sidwell44b21742015-01-19 01:44:02 +00002302/// Use small set to collect indirect bases. As this is only used
2303/// locally, there's no need to abstract the small size parameter.
2304typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2305
2306/// \brief Recursively add the bases of Type. Don't add Type itself.
2307static void
2308NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2309 const QualType &Type)
2310{
2311 // Even though the incoming type is a base, it might not be
2312 // a class -- it could be a template parm, for instance.
2313 if (auto Rec = Type->getAs<RecordType>()) {
2314 auto Decl = Rec->getAsCXXRecordDecl();
2315
2316 // Iterate over its bases.
2317 for (const auto &BaseSpec : Decl->bases()) {
2318 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2319 .getUnqualifiedType();
2320 if (Set.insert(Base).second)
2321 // If we've not already seen it, recurse.
2322 NoteIndirectBases(Context, Set, Base);
2323 }
2324 }
2325}
2326
Douglas Gregor463421d2009-03-03 04:44:36 +00002327/// \brief Performs the actual work of attaching the given base class
2328/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002329bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2330 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2331 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002332 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002333
2334 // Used to keep track of which base types we have already seen, so
2335 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002336 // that the key is always the unqualified canonical type of the base
2337 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002338 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2339
Nathan Sidwell44b21742015-01-19 01:44:02 +00002340 // Used to track indirect bases so we can see if a direct base is
2341 // ambiguous.
2342 IndirectBaseSet IndirectBaseTypes;
2343
Douglas Gregor29a92472008-10-22 17:49:05 +00002344 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002345 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002346 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002347 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002348 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002349 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002350 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002351
2352 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2353 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002354 // C++ [class.mi]p3:
2355 // A class shall not be specified as a direct base class of a
2356 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002357 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002358 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002359 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002360 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002361
2362 // Delete the duplicate base class specifier; we're going to
2363 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002364 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002365
2366 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002367 } else {
2368 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002369 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002370 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002371
2372 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002373 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002374 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2375
John McCalldb632ac2012-09-25 07:32:39 +00002376 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2378 if (Class->isInterface() &&
2379 (!RD->isInterface() ||
2380 KnownBase->getAccessSpecifier() != AS_public)) {
2381 // The Microsoft extension __interface does not permit bases that
2382 // are not themselves public interfaces.
2383 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2384 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2385 << RD->getSourceRange();
2386 Invalid = true;
2387 }
2388 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002389 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002390 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002391 }
2392 }
2393
2394 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002395 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002396
2397 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2398 // Check whether this direct base is inaccessible due to ambiguity.
2399 QualType BaseType = Bases[idx]->getType();
2400 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2401 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002402
Nathan Sidwell44b21742015-01-19 01:44:02 +00002403 if (IndirectBaseTypes.count(CanonicalBase)) {
2404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2405 /*DetectVirtual=*/true);
2406 bool found
2407 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2408 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002409 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002410
2411 if (Paths.isAmbiguous(CanonicalBase))
2412 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2413 << BaseType << getAmbiguousPathsDisplayString(Paths)
2414 << Bases[idx]->getSourceRange();
2415 else
2416 assert(Bases[idx]->isVirtual());
2417 }
2418
2419 // Delete the base class specifier, since its data has been copied
2420 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002421 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002422 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002423
2424 return Invalid;
2425}
2426
2427/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2428/// class, after checking whether there are any duplicate base
2429/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002430void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2431 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2432 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002433 return;
2434
2435 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002436 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002437}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002438
Douglas Gregor36d1b142009-10-06 17:59:45 +00002439/// \brief Determine whether the type \p Derived is a C++ class that is
2440/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002441bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002442 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002443 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002444
Douglas Gregor45bb4832013-03-26 23:36:30 +00002445 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002446 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002447 return false;
2448
Douglas Gregor45bb4832013-03-26 23:36:30 +00002449 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002450 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002451 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002452
2453 // If either the base or the derived type is invalid, don't try to
2454 // check whether one is derived from the other.
2455 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2456 return false;
2457
Richard Smithdb0ac552015-12-18 22:40:25 +00002458 // FIXME: In a modules build, do we need the entire path to be visible for us
2459 // to be able to use the inheritance relationship?
2460 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2461 return false;
2462
Richard Smith0f59cb32015-12-18 21:45:41 +00002463 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002464}
2465
2466/// \brief Determine whether the type \p Derived is a C++ class that is
2467/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002468bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2469 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002470 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002471 return false;
2472
Douglas Gregor45bb4832013-03-26 23:36:30 +00002473 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002474 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002475 return false;
2476
Douglas Gregor45bb4832013-03-26 23:36:30 +00002477 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002478 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002479 return false;
2480
Richard Smithdb0ac552015-12-18 22:40:25 +00002481 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2482 return false;
2483
Douglas Gregor36d1b142009-10-06 17:59:45 +00002484 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2485}
2486
Anders Carlssona70cff62010-04-24 19:06:50 +00002487void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002488 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002489 assert(BasePathArray.empty() && "Base path array must be empty!");
2490 assert(Paths.isRecordingPaths() && "Must record paths!");
2491
2492 const CXXBasePath &Path = Paths.front();
2493
2494 // We first go backward and check if we have a virtual base.
2495 // FIXME: It would be better if CXXBasePath had the base specifier for
2496 // the nearest virtual base.
2497 unsigned Start = 0;
2498 for (unsigned I = Path.size(); I != 0; --I) {
2499 if (Path[I - 1].Base->isVirtual()) {
2500 Start = I - 1;
2501 break;
2502 }
2503 }
2504
2505 // Now add all bases.
2506 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002507 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002508}
2509
Douglas Gregor36d1b142009-10-06 17:59:45 +00002510/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2511/// conversion (where Derived and Base are class types) is
2512/// well-formed, meaning that the conversion is unambiguous (and
2513/// that all of the base classes are accessible). Returns true
2514/// and emits a diagnostic if the code is ill-formed, returns false
2515/// otherwise. Loc is the location where this routine should point to
2516/// if there is an error, and Range is the source range to highlight
2517/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002518///
2519/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2520/// diagnostic for the respective type of error will be suppressed, but the
2521/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002522bool
2523Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002524 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002525 unsigned AmbigiousBaseConvID,
2526 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002527 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002528 CXXCastPath *BasePath,
2529 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002530 // First, determine whether the path from Derived to Base is
2531 // ambiguous. This is slightly more expensive than checking whether
2532 // the Derived to Base conversion exists, because here we need to
2533 // explore multiple paths to determine if there is an ambiguity.
2534 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2535 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002536 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002537 assert(DerivationOkay &&
2538 "Can only be used with a derived-to-base conversion");
2539 (void)DerivationOkay;
2540
2541 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002542 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002543 // Check that the base class can be accessed.
2544 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2545 InaccessibleBaseID)) {
2546 case AR_inaccessible:
2547 return true;
2548 case AR_accessible:
2549 case AR_dependent:
2550 case AR_delayed:
2551 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002552 }
John McCall5b0829a2010-02-10 09:31:12 +00002553 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002554
2555 // Build a base path if necessary.
2556 if (BasePath)
2557 BuildBasePathArray(Paths, *BasePath);
2558 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002559 }
2560
David Majnemer626032f2013-06-22 06:43:58 +00002561 if (AmbigiousBaseConvID) {
2562 // We know that the derived-to-base conversion is ambiguous, and
2563 // we're going to produce a diagnostic. Perform the derived-to-base
2564 // search just one more time to compute all of the possible paths so
2565 // that we can print them out. This is more expensive than any of
2566 // the previous derived-to-base checks we've done, but at this point
2567 // performance isn't as much of an issue.
2568 Paths.clear();
2569 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002570 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002571 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2572 (void)StillOkay;
2573
2574 // Build up a textual representation of the ambiguous paths, e.g.,
2575 // D -> B -> A, that will be used to illustrate the ambiguous
2576 // conversions in the diagnostic. We only print one of the paths
2577 // to each base class subobject.
2578 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2579
2580 Diag(Loc, AmbigiousBaseConvID)
2581 << Derived << Base << PathDisplayStr << Range << Name;
2582 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002583 return true;
2584}
2585
2586bool
2587Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002588 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002589 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002590 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002591 return CheckDerivedToBaseConversion(
2592 Derived, Base, diag::err_upcast_to_inaccessible_base,
2593 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2594 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002595}
2596
2597
2598/// @brief Builds a string representing ambiguous paths from a
2599/// specific derived class to different subobjects of the same base
2600/// class.
2601///
2602/// This function builds a string that can be used in error messages
2603/// to show the different paths that one can take through the
2604/// inheritance hierarchy to go from the derived class to different
2605/// subobjects of a base class. The result looks something like this:
2606/// @code
2607/// struct D -> struct B -> struct A
2608/// struct D -> struct C -> struct A
2609/// @endcode
2610std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2611 std::string PathDisplayStr;
2612 std::set<unsigned> DisplayedPaths;
2613 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2614 Path != Paths.end(); ++Path) {
2615 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2616 // We haven't displayed a path to this particular base
2617 // class subobject yet.
2618 PathDisplayStr += "\n ";
2619 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2620 for (CXXBasePath::const_iterator Element = Path->begin();
2621 Element != Path->end(); ++Element)
2622 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2623 }
2624 }
2625
2626 return PathDisplayStr;
2627}
2628
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002629//===----------------------------------------------------------------------===//
2630// C++ class member Handling
2631//===----------------------------------------------------------------------===//
2632
Abramo Bagnarad7340582010-06-05 05:09:32 +00002633/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002634bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2635 SourceLocation ASLoc,
2636 SourceLocation ColonLoc,
2637 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002638 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002639 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002640 ASLoc, ColonLoc);
2641 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002642 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002643}
2644
Richard Smith18f07db2012-08-06 03:25:17 +00002645/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002646void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002647 if (D->isInvalidDecl())
2648 return;
2649
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002650 // We only care about "override" and "final" declarations.
2651 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2652 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002653
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002654 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002655
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002656 // We can't check dependent instance methods.
2657 if (MD && MD->isInstance() &&
2658 (MD->getParent()->hasAnyDependentBases() ||
2659 MD->getType()->isDependentType()))
2660 return;
2661
2662 if (MD && !MD->isVirtual()) {
2663 // If we have a non-virtual method, check if if hides a virtual method.
2664 // (In that case, it's most likely the method has the wrong type.)
2665 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2666 FindHiddenVirtualMethods(MD, OverloadedMethods);
2667
2668 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002669 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2670 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002671 diag::override_keyword_hides_virtual_member_function)
2672 << "override" << (OverloadedMethods.size() > 1);
2673 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002674 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002675 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002676 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2677 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002678 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002679 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2680 MD->setInvalidDecl();
2681 return;
2682 }
2683 // Fall through into the general case diagnostic.
2684 // FIXME: We might want to attempt typo correction here.
2685 }
2686
2687 if (!MD || !MD->isVirtual()) {
2688 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2689 Diag(OA->getLocation(),
2690 diag::override_keyword_only_allowed_on_virtual_member_functions)
2691 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2692 D->dropAttr<OverrideAttr>();
2693 }
2694 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2695 Diag(FA->getLocation(),
2696 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002697 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2698 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002699 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002700 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002701 return;
2702 }
Richard Smith18f07db2012-08-06 03:25:17 +00002703
Richard Smith18f07db2012-08-06 03:25:17 +00002704 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002705 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002706 // does not override a member function of a base class, the program is
2707 // ill-formed.
2708 bool HasOverriddenMethods =
2709 MD->begin_overridden_methods() != MD->end_overridden_methods();
2710 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2711 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2712 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002713}
2714
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002715void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2716 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2717 return;
2718 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Richard Trieu07c93382017-03-01 03:07:55 +00002719 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002720 return;
2721
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002722 SourceLocation Loc = MD->getLocation();
2723 SourceLocation SpellingLoc = Loc;
2724 if (getSourceManager().isMacroArgExpansion(Loc))
2725 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2726 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2727 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002728 return;
Richard Trieu07c93382017-03-01 03:07:55 +00002729
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002730 if (MD->size_overridden_methods() > 0) {
Richard Trieu07c93382017-03-01 03:07:55 +00002731 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2732 ? diag::warn_destructor_marked_not_override_overriding
2733 : diag::warn_function_marked_not_override_overriding;
2734 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002735 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2736 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2737 }
2738}
2739
Richard Smith18f07db2012-08-06 03:25:17 +00002740/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002741/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002742/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002743bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2744 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002745 FinalAttr *FA = Old->getAttr<FinalAttr>();
2746 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002747 return false;
2748
2749 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002750 << New->getDeclName()
2751 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002752 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2753 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002754}
2755
Daniel Jasper0baec5492012-06-06 08:32:04 +00002756static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002757 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2758 // FIXME: Destruction of ObjC lifetime types has side-effects.
2759 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2760 return !RD->isCompleteDefinition() ||
2761 !RD->hasTrivialDefaultConstructor() ||
2762 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002763 return false;
2764}
2765
John McCall5e77d762013-04-16 07:28:30 +00002766static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002767 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002768 if (it->isDeclspecPropertyAttribute())
2769 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002770 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002771}
2772
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00002773// Check if there is a field shadowing.
2774void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2775 DeclarationName FieldName,
2776 const CXXRecordDecl *RD) {
2777 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2778 return;
2779
2780 // To record a shadowed field in a base
2781 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2782 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2783 CXXBasePath &Path) {
2784 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2785 // Record an ambiguous path directly
2786 if (Bases.find(Base) != Bases.end())
2787 return true;
2788 for (const auto Field : Base->lookup(FieldName)) {
2789 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2790 Field->getAccess() != AS_private) {
2791 assert(Field->getAccess() != AS_none);
2792 assert(Bases.find(Base) == Bases.end());
2793 Bases[Base] = Field;
2794 return true;
2795 }
2796 }
2797 return false;
2798 };
2799
2800 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2801 /*DetectVirtual=*/true);
2802 if (!RD->lookupInBases(FieldShadowed, Paths))
2803 return;
2804
2805 for (const auto &P : Paths) {
2806 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2807 auto It = Bases.find(Base);
2808 // Skip duplicated bases
2809 if (It == Bases.end())
2810 continue;
2811 auto BaseField = It->second;
2812 assert(BaseField->getAccess() != AS_private);
2813 if (AS_none !=
2814 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2815 Diag(Loc, diag::warn_shadow_field)
2816 << FieldName.getAsString() << RD->getName() << Base->getName();
2817 Diag(BaseField->getLocation(), diag::note_shadow_field);
2818 Bases.erase(It);
2819 }
2820 }
2821}
2822
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002823/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2824/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002825/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002826/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2827/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002828NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002829Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002830 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002831 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002832 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002833 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002834 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2835 DeclarationName Name = NameInfo.getName();
2836 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002837
2838 // For anonymous bitfields, the location should point to the type.
2839 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002840 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002841
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002842 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002843
John McCallb1cd7da2010-06-04 08:34:12 +00002844 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002845 assert(!DS.isFriendSpecified());
2846
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002847 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002848
John McCalldb632ac2012-09-25 07:32:39 +00002849 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2850 // The Microsoft extension __interface only permits public member functions
2851 // and prohibits constructors, destructors, operators, non-public member
2852 // functions, static methods and data members.
2853 unsigned InvalidDecl;
2854 bool ShowDeclName = true;
2855 if (!isFunc)
2856 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2857 else if (AS != AS_public)
2858 InvalidDecl = 2;
2859 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2860 InvalidDecl = 3;
2861 else switch (Name.getNameKind()) {
2862 case DeclarationName::CXXConstructorName:
2863 InvalidDecl = 4;
2864 ShowDeclName = false;
2865 break;
2866
2867 case DeclarationName::CXXDestructorName:
2868 InvalidDecl = 5;
2869 ShowDeclName = false;
2870 break;
2871
2872 case DeclarationName::CXXOperatorName:
2873 case DeclarationName::CXXConversionFunctionName:
2874 InvalidDecl = 6;
2875 break;
2876
2877 default:
2878 InvalidDecl = 0;
2879 break;
2880 }
2881
2882 if (InvalidDecl) {
2883 if (ShowDeclName)
2884 Diag(Loc, diag::err_invalid_member_in_interface)
2885 << (InvalidDecl-1) << Name;
2886 else
2887 Diag(Loc, diag::err_invalid_member_in_interface)
2888 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002889 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002890 }
2891 }
2892
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002893 // C++ 9.2p6: A member shall not be declared to have automatic storage
2894 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002895 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2896 // data members and cannot be applied to names declared const or static,
2897 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002898 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002899 case DeclSpec::SCS_unspecified:
2900 case DeclSpec::SCS_typedef:
2901 case DeclSpec::SCS_static:
2902 break;
2903 case DeclSpec::SCS_mutable:
2904 if (isFunc) {
2905 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002906
Richard Smithb4a9e862013-04-12 22:46:28 +00002907 // FIXME: It would be nicer if the keyword was ignored only for this
2908 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002909 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002910 }
2911 break;
2912 default:
2913 Diag(DS.getStorageClassSpecLoc(),
2914 diag::err_storageclass_invalid_for_member);
2915 D.getMutableDeclSpec().ClearStorageClassSpecs();
2916 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002917 }
2918
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002919 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2920 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002921 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002922
David Blaikie35506f82013-01-30 01:22:18 +00002923 if (DS.isConstexprSpecified() && isInstField) {
2924 SemaDiagnosticBuilder B =
2925 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2926 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2927 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002928 B << 0 << 0;
2929 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2930 B << FixItHint::CreateRemoval(ConstexprLoc);
2931 else {
2932 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2933 D.getMutableDeclSpec().ClearConstexprSpec();
2934 const char *PrevSpec;
2935 unsigned DiagID;
2936 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2937 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2938 (void)Failed;
2939 assert(!Failed && "Making a constexpr member const shouldn't fail");
2940 }
David Blaikie35506f82013-01-30 01:22:18 +00002941 } else {
2942 B << 1;
2943 const char *PrevSpec;
2944 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002945 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002946 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2947 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002948 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002949 "This is the only DeclSpec that should fail to be applied");
2950 B << 1;
2951 } else {
2952 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2953 isInstField = false;
2954 }
2955 }
2956 }
2957
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002958 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002959 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002960 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002961
2962 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002963 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002964 Diag(Loc, diag::err_bad_variable_name)
2965 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002967 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002968
Benjamin Kramer365082d2012-05-19 16:34:46 +00002969 IdentifierInfo *II = Name.getAsIdentifierInfo();
2970
Douglas Gregor7c26c042011-09-21 14:40:46 +00002971 // Member field could not be with "template" keyword.
2972 // So TemplateParameterLists should be empty in this case.
2973 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002974 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002975 if (TemplateParams->size()) {
2976 // There is no such thing as a member field template.
2977 Diag(D.getIdentifierLoc(), diag::err_template_member)
2978 << II
2979 << SourceRange(TemplateParams->getTemplateLoc(),
2980 TemplateParams->getRAngleLoc());
2981 } else {
2982 // There is an extraneous 'template<>' for this member.
2983 Diag(TemplateParams->getTemplateLoc(),
2984 diag::err_template_member_noparams)
2985 << II
2986 << SourceRange(TemplateParams->getTemplateLoc(),
2987 TemplateParams->getRAngleLoc());
2988 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002989 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002990 }
2991
Douglas Gregora007d362010-10-13 22:19:53 +00002992 if (SS.isSet() && !SS.isInvalid()) {
2993 // The user provided a superfluous scope specifier inside a class
2994 // definition:
2995 //
2996 // class X {
2997 // int X::member;
2998 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002999 if (DeclContext *DC = computeDeclContext(SS, false))
3000 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00003001 else
3002 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3003 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00003004
Douglas Gregora007d362010-10-13 22:19:53 +00003005 SS.clear();
3006 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00003007
John McCall5e77d762013-04-16 07:28:30 +00003008 AttributeList *MSPropertyAttr =
3009 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003010 if (MSPropertyAttr) {
3011 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3012 BitWidth, InitStyle, AS, MSPropertyAttr);
3013 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003014 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003015 isInstField = false;
3016 } else {
3017 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3018 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00003019 if (!Member)
3020 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003021 }
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00003022
Saleem Abdulrasoolb893ed22017-02-11 17:24:04 +00003023 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003024 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003025 Member = HandleDeclarator(S, D, TemplateParameterLists);
3026 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003027 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003028
3029 // Non-instance-fields can't have a bitfield.
3030 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003031 if (Member->isInvalidDecl()) {
3032 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00003033 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003034 // C++ 9.6p3: A bit-field shall not be a static member.
3035 // "static member 'A' cannot be a bit-field"
3036 Diag(Loc, diag::err_static_not_bitfield)
3037 << Name << BitWidth->getSourceRange();
3038 } else if (isa<TypedefDecl>(Member)) {
3039 // "typedef member 'x' cannot be a bit-field"
3040 Diag(Loc, diag::err_typedef_not_bitfield)
3041 << Name << BitWidth->getSourceRange();
3042 } else {
3043 // A function typedef ("typedef int f(); f a;").
3044 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3045 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00003046 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00003047 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00003048 }
Mike Stump11289f42009-09-09 15:08:12 +00003049
Craig Topperc3ec1492014-05-26 06:22:03 +00003050 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00003051 Member->setInvalidDecl();
3052 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00003053
3054 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00003055
Larisse Voufo39a1e502013-08-06 01:03:05 +00003056 // If we have declared a member function template or static data member
3057 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00003058 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3059 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003060 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3061 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003062 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003063
Richard Smith18f07db2012-08-06 03:25:17 +00003064 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003065 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003066 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003067 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3068 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003069
Douglas Gregorf2f08062011-03-08 17:10:18 +00003070 if (VS.getLastLocation().isValid()) {
3071 // Update the end location of a method that has a virt-specifiers.
3072 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3073 MD->setRangeEnd(VS.getLastLocation());
3074 }
Richard Smith18f07db2012-08-06 03:25:17 +00003075
Anders Carlssonc87f8612011-01-20 06:29:02 +00003076 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003077
Douglas Gregor92751d42008-11-17 22:58:34 +00003078 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003079
Daniel Jasper0baec5492012-06-06 08:32:04 +00003080 if (isInstField) {
3081 FieldDecl *FD = cast<FieldDecl>(Member);
3082 FieldCollector->Add(FD);
3083
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003084 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003085 // Remember all explicit private FieldDecls that have a name, no side
3086 // effects and are not part of a dependent type declaration.
3087 if (!FD->isImplicit() && FD->getDeclName() &&
3088 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003089 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003090 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003091 !InitializationHasSideEffects(*FD))
3092 UnusedPrivateFields.insert(FD);
3093 }
3094 }
3095
John McCall48871652010-08-21 09:40:31 +00003096 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003097}
3098
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003099namespace {
3100 class UninitializedFieldVisitor
3101 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3102 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003103 // List of Decls to generate a warning on. Also remove Decls that become
3104 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003105 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003106 // List of base classes of the record. Classes are removed after their
3107 // initializers.
3108 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003109 // Vector of decls to be removed from the Decl set prior to visiting the
3110 // nodes. These Decls may have been initialized in the prior initializer.
3111 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003112 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003113 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003114 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003115 // InitList is true, special case initialization of FieldDecls matching
3116 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003117 bool InitList;
3118 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003119 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3120
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003121 public:
3122 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003123 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003124 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3125 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3126 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3127 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003128
Richard Trieufa1d0a72014-10-17 20:56:10 +00003129 // Returns true if the use of ME is not an uninitialized use.
3130 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3131 bool CheckReferenceOnly) {
3132 llvm::SmallVector<FieldDecl*, 4> Fields;
3133 bool ReferenceField = false;
3134 while (ME) {
3135 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3136 if (!FD)
3137 return false;
3138 Fields.push_back(FD);
3139 if (FD->getType()->isReferenceType())
3140 ReferenceField = true;
3141 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3142 }
3143
3144 // Binding a reference to an unintialized field is not an
3145 // uninitialized use.
3146 if (CheckReferenceOnly && !ReferenceField)
3147 return true;
3148
3149 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3150 // Discard the first field since it is the field decl that is being
3151 // initialized.
3152 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3153 UsedFieldIndex.push_back((*I)->getFieldIndex());
3154 }
3155
3156 for (auto UsedIter = UsedFieldIndex.begin(),
3157 UsedEnd = UsedFieldIndex.end(),
3158 OrigIter = InitFieldIndex.begin(),
3159 OrigEnd = InitFieldIndex.end();
3160 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3161 if (*UsedIter < *OrigIter)
3162 return true;
3163 if (*UsedIter > *OrigIter)
3164 break;
3165 }
3166
3167 return false;
3168 }
3169
Richard Trieu2d779b92014-10-01 03:44:58 +00003170 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3171 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003172 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3173 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003174
Richard Trieu1bc22c12013-09-13 03:20:53 +00003175 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3176 // or union.
3177 MemberExpr *FieldME = ME;
3178
Richard Trieu2d779b92014-10-01 03:44:58 +00003179 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3180
Richard Trieu1bc22c12013-09-13 03:20:53 +00003181 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003182 while (MemberExpr *SubME =
3183 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003184
Richard Trieufa1d0a72014-10-17 20:56:10 +00003185 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003186 return;
3187
Richard Trieufa1d0a72014-10-17 20:56:10 +00003188 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003189 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003190 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003191
Richard Trieu2d779b92014-10-01 03:44:58 +00003192 if (!FieldME->getType().isPODType(S.Context))
3193 AllPODFields = false;
3194
Richard Trieu3630c392014-11-21 03:10:30 +00003195 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003196 }
3197
Richard Trieu3630c392014-11-21 03:10:30 +00003198 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003199 return;
3200
Richard Trieu2d779b92014-10-01 03:44:58 +00003201 if (AddressOf && AllPODFields)
3202 return;
3203
Richard Trieu406e65c2013-09-20 03:03:06 +00003204 ValueDecl* FoundVD = FieldME->getMemberDecl();
3205
Richard Trieu3630c392014-11-21 03:10:30 +00003206 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3207 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3208 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3209 }
3210
3211 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3212 QualType T = BaseCast->getType();
3213 if (T->isPointerType() &&
3214 BaseClasses.count(T->getPointeeType())) {
3215 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3216 << T->getPointeeType() << FoundVD;
3217 }
3218 }
3219 }
3220
Richard Trieuef64e942013-10-25 00:56:00 +00003221 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003222 return;
3223
Richard Trieuef64e942013-10-25 00:56:00 +00003224 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003225
Richard Trieufa1d0a72014-10-17 20:56:10 +00003226 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3227 // Special checking for initializer lists.
3228 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3229 return;
3230 }
3231 } else {
3232 // Prevent double warnings on use of unbounded references.
3233 if (CheckReferenceOnly && !IsReference)
3234 return;
3235 }
Richard Trieuef64e942013-10-25 00:56:00 +00003236
3237 unsigned diag = IsReference
3238 ? diag::warn_reference_field_is_uninit
3239 : diag::warn_field_is_uninit;
3240 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3241 if (Constructor)
3242 S.Diag(Constructor->getLocation(),
3243 diag::note_uninit_in_this_constructor)
3244 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3245
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003246 }
3247
Richard Trieu2d779b92014-10-01 03:44:58 +00003248 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003249 E = E->IgnoreParens();
3250
3251 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003252 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3253 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003254 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003255 }
3256
3257 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003258 Visit(CO->getCond());
3259 HandleValue(CO->getTrueExpr(), AddressOf);
3260 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003261 return;
3262 }
3263
3264 if (BinaryConditionalOperator *BCO =
3265 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003266 Visit(BCO->getCond());
3267 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003268 return;
3269 }
3270
Richard Trieuabf6ec42014-08-27 22:15:10 +00003271 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003272 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003273 return;
3274 }
3275
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3277 switch (BO->getOpcode()) {
3278 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003279 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003280 case(BO_PtrMemD):
3281 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003282 HandleValue(BO->getLHS(), AddressOf);
3283 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003284 return;
3285 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003286 Visit(BO->getLHS());
3287 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003288 return;
3289 }
3290 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003291
3292 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003293 }
3294
Richard Trieufa1d0a72014-10-17 20:56:10 +00003295 void CheckInitListExpr(InitListExpr *ILE) {
3296 InitFieldIndex.push_back(0);
3297 for (auto Child : ILE->children()) {
3298 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3299 CheckInitListExpr(SubList);
3300 } else {
3301 Visit(Child);
3302 }
3303 ++InitFieldIndex.back();
3304 }
3305 InitFieldIndex.pop_back();
3306 }
3307
Richard Trieu8d08a272014-08-28 03:23:47 +00003308 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003309 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003310 // Remove Decls that may have been initialized in the previous
3311 // initializer.
3312 for (ValueDecl* VD : DeclsToRemove)
3313 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003314 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003315
Richard Trieu8d08a272014-08-28 03:23:47 +00003316 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003317 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3318
3319 if (ILE && Field) {
3320 InitList = true;
3321 InitListFieldDecl = Field;
3322 InitFieldIndex.clear();
3323 CheckInitListExpr(ILE);
3324 } else {
3325 InitList = false;
3326 Visit(E);
3327 }
3328
Richard Trieu8d08a272014-08-28 03:23:47 +00003329 if (Field)
3330 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003331 if (BaseClass)
3332 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003333 }
3334
Richard Trieu1bc22c12013-09-13 03:20:53 +00003335 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003336 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003337 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003338 }
3339
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003340 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003341 if (E->getCastKind() == CK_LValueToRValue) {
3342 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3343 return;
3344 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003345
3346 Inherited::VisitImplicitCastExpr(E);
3347 }
3348
Richard Trieu1bc22c12013-09-13 03:20:53 +00003349 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003350 if (E->getConstructor()->isCopyConstructor()) {
3351 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003352 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3353 if (ILE->getNumInits() == 1)
3354 ArgExpr = ILE->getInit(0);
3355 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3356 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003357 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003358 HandleValue(ArgExpr, false /*AddressOf*/);
3359 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003360 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003361 Inherited::VisitCXXConstructExpr(E);
3362 }
3363
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003364 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3365 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003366 if (isa<MemberExpr>(Callee)) {
3367 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003368 for (auto Arg : E->arguments())
3369 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003370 return;
3371 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003372
3373 Inherited::VisitCXXMemberCallExpr(E);
3374 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003375
Richard Trieu11fd0792014-08-26 04:30:55 +00003376 void VisitCallExpr(CallExpr *E) {
3377 // Treat std::move as a use.
3378 if (E->getNumArgs() == 1) {
3379 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003380 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3381 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003382 HandleValue(E->getArg(0), false /*AddressOf*/);
3383 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003384 }
3385 }
3386 }
3387
3388 Inherited::VisitCallExpr(E);
3389 }
3390
Richard Trieud4a01362014-10-31 21:10:22 +00003391 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3392 Expr *Callee = E->getCallee();
3393
3394 if (isa<UnresolvedLookupExpr>(Callee))
3395 return Inherited::VisitCXXOperatorCallExpr(E);
3396
3397 Visit(Callee);
3398 for (auto Arg : E->arguments())
3399 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3400 }
3401
Richard Trieu406e65c2013-09-20 03:03:06 +00003402 void VisitBinaryOperator(BinaryOperator *E) {
3403 // If a field assignment is detected, remove the field from the
3404 // uninitiailized field set.
3405 if (E->getOpcode() == BO_Assign)
3406 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3407 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003408 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003409 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003410
Richard Trieu52b8b602014-09-25 01:15:40 +00003411 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003412 HandleValue(E->getLHS(), false /*AddressOf*/);
3413 Visit(E->getRHS());
3414 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003415 }
3416
Richard Trieu406e65c2013-09-20 03:03:06 +00003417 Inherited::VisitBinaryOperator(E);
3418 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003419
3420 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003421 if (E->isIncrementDecrementOp()) {
3422 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3423 return;
3424 }
3425 if (E->getOpcode() == UO_AddrOf) {
3426 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3427 HandleValue(ME->getBase(), true /*AddressOf*/);
3428 return;
3429 }
3430 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003431
3432 Inherited::VisitUnaryOperator(E);
3433 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003434 };
Richard Trieuef64e942013-10-25 00:56:00 +00003435
3436 // Diagnose value-uses of fields to initialize themselves, e.g.
3437 // foo(foo)
3438 // where foo is not also a parameter to the constructor.
3439 // Also diagnose across field uninitialized use such as
3440 // x(y), y(x)
3441 // TODO: implement -Wuninitialized and fold this into that framework.
3442 static void DiagnoseUninitializedFields(
3443 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3444
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003445 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3446 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003447 return;
3448 }
3449
3450 if (Constructor->isInvalidDecl())
3451 return;
3452
3453 const CXXRecordDecl *RD = Constructor->getParent();
3454
Richard Trieu353a4b42014-10-22 05:21:59 +00003455 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003456 return;
3457
Richard Trieuef64e942013-10-25 00:56:00 +00003458 // Holds fields that are uninitialized.
3459 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3460
3461 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003462 for (auto *I : RD->decls()) {
3463 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003464 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003465 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003466 UninitializedFields.insert(IFD->getAnonField());
3467 }
3468 }
3469
Richard Trieu3630c392014-11-21 03:10:30 +00003470 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3471 for (auto I : RD->bases())
3472 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3473
3474 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003475 return;
3476
3477 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003478 UninitializedFields,
3479 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003480
Aaron Ballman0ad78302014-03-13 17:34:31 +00003481 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003482 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003483 break;
3484
Aaron Ballman0ad78302014-03-13 17:34:31 +00003485 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003486 if (!InitExpr)
3487 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003488
Richard Trieu8d08a272014-08-28 03:23:47 +00003489 if (CXXDefaultInitExpr *Default =
3490 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3491 InitExpr = Default->getExpr();
3492 if (!InitExpr)
3493 continue;
3494 // In class initializers will point to the constructor.
3495 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003496 FieldInit->getAnyMember(),
3497 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003498 } else {
3499 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003500 FieldInit->getAnyMember(),
3501 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003502 }
Richard Trieuef64e942013-10-25 00:56:00 +00003503 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003504 }
3505} // namespace
3506
Richard Smith74108172014-01-17 03:11:34 +00003507/// \brief Enter a new C++ default initializer scope. After calling this, the
3508/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3509/// parsing or instantiating the initializer failed.
3510void Sema::ActOnStartCXXInClassMemberInitializer() {
3511 // Create a synthetic function scope to represent the call to the constructor
3512 // that notionally surrounds a use of this initializer.
3513 PushFunctionScope();
3514}
3515
3516/// \brief This is invoked after parsing an in-class initializer for a
3517/// non-static C++ class member, and after instantiating an in-class initializer
3518/// in a class template. Such actions are deferred until the class is complete.
3519void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3520 SourceLocation InitLoc,
3521 Expr *InitExpr) {
3522 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003523 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003524
David Majnemer87ff66c2014-12-13 11:34:16 +00003525 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3526 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003527 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003528
3529 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003530 D->setInvalidDecl();
3531 if (FD)
3532 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003533 return;
3534 }
3535
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003536 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3537 FD->setInvalidDecl();
3538 FD->removeInClassInitializer();
3539 return;
3540 }
3541
Richard Smith938f40b2011-06-11 17:19:42 +00003542 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003543 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003544 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003545 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003546 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003547 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003548 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3549 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003550 if (Init.isInvalid()) {
3551 FD->setInvalidDecl();
3552 return;
3553 }
Richard Smith938f40b2011-06-11 17:19:42 +00003554 }
3555
Richard Smith945f8d32013-01-14 22:39:08 +00003556 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003557 // The initialization of each base and member constitutes a
3558 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003559 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003560 if (Init.isInvalid()) {
3561 FD->setInvalidDecl();
3562 return;
3563 }
3564
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003565 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003566
3567 FD->setInClassInitializer(InitExpr);
3568}
3569
Douglas Gregor15e77a22009-12-31 09:10:24 +00003570/// \brief Find the direct and/or virtual base specifiers that
3571/// correspond to the given base type, for use in base initialization
3572/// within a constructor.
3573static bool FindBaseInitializer(Sema &SemaRef,
3574 CXXRecordDecl *ClassDecl,
3575 QualType BaseType,
3576 const CXXBaseSpecifier *&DirectBaseSpec,
3577 const CXXBaseSpecifier *&VirtualBaseSpec) {
3578 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003579 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003580 for (const auto &Base : ClassDecl->bases()) {
3581 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003582 // We found a direct base of this type. That's what we're
3583 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003584 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003585 break;
3586 }
3587 }
3588
3589 // Check for a virtual base class.
3590 // FIXME: We might be able to short-circuit this if we know in advance that
3591 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003592 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003593 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3594 // We haven't found a base yet; search the class hierarchy for a
3595 // virtual base class.
3596 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3597 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003598 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3599 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003600 BaseType, Paths)) {
3601 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3602 Path != Paths.end(); ++Path) {
3603 if (Path->back().Base->isVirtual()) {
3604 VirtualBaseSpec = Path->back().Base;
3605 break;
3606 }
3607 }
3608 }
3609 }
3610
3611 return DirectBaseSpec || VirtualBaseSpec;
3612}
3613
Sebastian Redla74948d2011-09-24 17:48:25 +00003614/// \brief Handle a C++ member initializer using braced-init-list syntax.
3615MemInitResult
3616Sema::ActOnMemInitializer(Decl *ConstructorD,
3617 Scope *S,
3618 CXXScopeSpec &SS,
3619 IdentifierInfo *MemberOrBase,
3620 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003621 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003622 SourceLocation IdLoc,
3623 Expr *InitList,
3624 SourceLocation EllipsisLoc) {
3625 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003626 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003627 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003628}
3629
3630/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003631MemInitResult
John McCall48871652010-08-21 09:40:31 +00003632Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003633 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003634 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003635 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003636 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003637 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003638 SourceLocation IdLoc,
3639 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003640 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003641 SourceLocation RParenLoc,
3642 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003643 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003644 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003645 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003646 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003647}
3648
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003649namespace {
3650
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003651// Callback to only accept typo corrections that can be a valid C++ member
3652// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003653class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003654public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003655 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3656 : ClassDecl(ClassDecl) {}
3657
Craig Toppera798a9d2014-03-02 09:32:10 +00003658 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003659 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3660 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3661 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003662 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003663 }
3664 return false;
3665 }
3666
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003667private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003668 CXXRecordDecl *ClassDecl;
3669};
3670
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003671}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003672
Sebastian Redla74948d2011-09-24 17:48:25 +00003673/// \brief Handle a C++ member initializer.
3674MemInitResult
3675Sema::BuildMemInitializer(Decl *ConstructorD,
3676 Scope *S,
3677 CXXScopeSpec &SS,
3678 IdentifierInfo *MemberOrBase,
3679 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003680 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003681 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003682 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003683 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003684 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3685 if (!Res.isUsable())
3686 return true;
3687 Init = Res.get();
3688
Douglas Gregor71a57182009-06-22 23:20:33 +00003689 if (!ConstructorD)
3690 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003691
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003692 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003693
3694 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003695 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003696 if (!Constructor) {
3697 // The user wrote a constructor initializer on a function that is
3698 // not a C++ constructor. Ignore the error for now, because we may
3699 // have more member initializers coming; we'll diagnose it just
3700 // once in ActOnMemInitializers.
3701 return true;
3702 }
3703
3704 CXXRecordDecl *ClassDecl = Constructor->getParent();
3705
3706 // C++ [class.base.init]p2:
3707 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003708 // constructor's class and, if not found in that scope, are looked
3709 // up in the scope containing the constructor's definition.
3710 // [Note: if the constructor's class contains a member with the
3711 // same name as a direct or virtual base class of the class, a
3712 // mem-initializer-id naming the member or base class and composed
3713 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003714 // mem-initializer-id for the hidden base class may be specified
3715 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003716 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003717 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003718 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003719 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003720 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003721 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3722 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003723 if (EllipsisLoc.isValid())
3724 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003725 << MemberOrBase
3726 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003727
Sebastian Redla9351792012-02-11 23:51:47 +00003728 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003729 }
Francois Pichetd583da02010-12-04 09:14:42 +00003730 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003731 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003732 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003733 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003734 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003735
3736 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003737 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003738 } else if (DS.getTypeSpecType() == TST_decltype) {
3739 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
Richard Smithef2cd8f2017-02-08 20:39:08 +00003740 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3741 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3742 return true;
John McCallb5a0d312009-12-21 10:41:20 +00003743 } else {
3744 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3745 LookupParsedName(R, S, &SS);
3746
3747 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3748 if (!TyD) {
3749 if (R.isAmbiguous()) return true;
3750
John McCallda6841b2010-04-09 19:01:14 +00003751 // We don't want access-control diagnostics here.
3752 R.suppressDiagnostics();
3753
Douglas Gregora3b624a2010-01-19 06:46:48 +00003754 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3755 bool NotUnknownSpecialization = false;
3756 DeclContext *DC = computeDeclContext(SS, false);
3757 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3758 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3759
3760 if (!NotUnknownSpecialization) {
3761 // When the scope specifier can refer to a member of an unknown
3762 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003763 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3764 SS.getWithLocInContext(Context),
3765 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003766 if (BaseType.isNull())
3767 return true;
3768
Douglas Gregora3b624a2010-01-19 06:46:48 +00003769 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003770 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003771 }
3772 }
3773
Douglas Gregor15e77a22009-12-31 09:10:24 +00003774 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003775 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003776 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003777 (Corr = CorrectTypo(
3778 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3779 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3780 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003781 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003782 // We have found a non-static data member with a similar
3783 // name to what was typed; complain and initialize that
3784 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003785 diagnoseTypo(Corr,
3786 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3787 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003788 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003789 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003790 const CXXBaseSpecifier *DirectBaseSpec;
3791 const CXXBaseSpecifier *VirtualBaseSpec;
3792 if (FindBaseInitializer(*this, ClassDecl,
3793 Context.getTypeDeclType(Type),
3794 DirectBaseSpec, VirtualBaseSpec)) {
3795 // We have found a direct or virtual base class with a
3796 // similar name to what was typed; complain and initialize
3797 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003798 diagnoseTypo(Corr,
3799 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3800 << MemberOrBase << false,
3801 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003802
Richard Smithf9b15102013-08-17 00:46:16 +00003803 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3804 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003805 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003806 diag::note_base_class_specified_here)
3807 << BaseSpec->getType()
3808 << BaseSpec->getSourceRange();
3809
Douglas Gregor15e77a22009-12-31 09:10:24 +00003810 TyD = Type;
3811 }
3812 }
3813 }
3814
Douglas Gregora3b624a2010-01-19 06:46:48 +00003815 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003816 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003817 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003818 return true;
3819 }
John McCallb5a0d312009-12-21 10:41:20 +00003820 }
3821
Douglas Gregora3b624a2010-01-19 06:46:48 +00003822 if (BaseType.isNull()) {
3823 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003824 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003825 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003826 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3827 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003828 TInfo = Context.CreateTypeSourceInfo(BaseType);
3829 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3830 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3831 TL.setElaboratedKeywordLoc(SourceLocation());
3832 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3833 }
John McCallb5a0d312009-12-21 10:41:20 +00003834 }
3835 }
Mike Stump11289f42009-09-09 15:08:12 +00003836
John McCallbcd03502009-12-07 02:54:59 +00003837 if (!TInfo)
3838 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003839
Sebastian Redla9351792012-02-11 23:51:47 +00003840 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003841}
3842
Chandler Carruth599deef2011-09-03 01:14:15 +00003843/// Checks a member initializer expression for cases where reference (or
3844/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003845static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3846 Expr *Init,
3847 SourceLocation IdLoc) {
3848 QualType MemberTy = Member->getType();
3849
3850 // We only handle pointers and references currently.
3851 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3852 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3853 return;
3854
3855 const bool IsPointer = MemberTy->isPointerType();
3856 if (IsPointer) {
3857 if (const UnaryOperator *Op
3858 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3859 // The only case we're worried about with pointers requires taking the
3860 // address.
3861 if (Op->getOpcode() != UO_AddrOf)
3862 return;
3863
3864 Init = Op->getSubExpr();
3865 } else {
3866 // We only handle address-of expression initializers for pointers.
3867 return;
3868 }
3869 }
3870
Richard Smithe3b28bc2013-06-12 21:51:50 +00003871 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003872 // We only warn when referring to a non-reference parameter declaration.
3873 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3874 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003875 return;
3876
3877 S.Diag(Init->getExprLoc(),
3878 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3879 : diag::warn_bind_ref_member_to_parameter)
3880 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003881 } else {
3882 // Other initializers are fine.
3883 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003884 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003885
3886 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3887 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003888}
3889
John McCallfaf5fb42010-08-26 23:41:50 +00003890MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003891Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003892 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003893 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3894 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3895 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003896 "Member must be a FieldDecl or IndirectFieldDecl");
3897
Sebastian Redla9351792012-02-11 23:51:47 +00003898 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003899 return true;
3900
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003901 if (Member->isInvalidDecl())
3902 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003903
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003904 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003905 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003906 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003907 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003908 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003909 } else {
3910 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003911 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003912 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003913
Sebastian Redla9351792012-02-11 23:51:47 +00003914 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003915
Sebastian Redla9351792012-02-11 23:51:47 +00003916 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003917 // Can't check initialization for a member of dependent type or when
3918 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003919 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003920 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003921 bool InitList = false;
3922 if (isa<InitListExpr>(Init)) {
3923 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003924 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003925 }
3926
Chandler Carruthd44c3102010-12-06 09:23:57 +00003927 // Initialize the member.
3928 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003929 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3930 : InitializedEntity::InitializeMember(IndirectMember,
3931 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003932 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003933 InitList ? InitializationKind::CreateDirectList(IdLoc)
3934 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3935 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003936
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003937 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003938 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3939 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003940 if (MemberInit.isInvalid())
3941 return true;
3942
Richard Smith736a9472013-06-12 20:42:33 +00003943 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3944
Richard Smith945f8d32013-01-14 22:39:08 +00003945 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003946 // The initialization of each base and member constitutes a
3947 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003948 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003949 if (MemberInit.isInvalid())
3950 return true;
3951
Richard Smithd59b8322012-12-19 01:39:02 +00003952 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003953 }
3954
Chandler Carruthd44c3102010-12-06 09:23:57 +00003955 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003956 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3957 InitRange.getBegin(), Init,
3958 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003959 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003960 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3961 InitRange.getBegin(), Init,
3962 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003963 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003964}
3965
John McCallfaf5fb42010-08-26 23:41:50 +00003966MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003967Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003968 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003969 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003970 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003971 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003972 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003973 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003974
Sebastian Redl0501c632012-02-12 16:37:36 +00003975 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003976 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003977 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3978 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003979 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003980 }
3981
Sebastian Redla9351792012-02-11 23:51:47 +00003982 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003983 // Initialize the object.
3984 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3985 QualType(ClassDecl->getTypeForDecl(), 0));
3986 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003987 InitList ? InitializationKind::CreateDirectList(NameLoc)
3988 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3989 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003990 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003991 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003992 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003993 if (DelegationInit.isInvalid())
3994 return true;
3995
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003996 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3997 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003998
Richard Smith945f8d32013-01-14 22:39:08 +00003999 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00004000 // The initialization of each base and member constitutes a
4001 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004002 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4003 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00004004 if (DelegationInit.isInvalid())
4005 return true;
4006
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004007 // If we are in a dependent context, template instantiation will
4008 // perform this type-checking again. Just save the arguments that we
4009 // received in a ParenListExpr.
4010 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4011 // of the information that we have about the base
4012 // initializer. However, deconstructing the ASTs is a dicey process,
4013 // and this approach is far more likely to get the corner cases right.
4014 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004015 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004016
Sebastian Redla9351792012-02-11 23:51:47 +00004017 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004018 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004019 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004020}
4021
4022MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00004023Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00004024 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004025 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004026 SourceLocation BaseLoc
4027 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00004028
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004029 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4030 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4031 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4032
4033 // C++ [class.base.init]p2:
4034 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00004035 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004036 // of that class, the mem-initializer is ill-formed. A
4037 // mem-initializer-list can initialize a base class using any
4038 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00004039 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004040
Sebastian Redla9351792012-02-11 23:51:47 +00004041 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00004042 if (EllipsisLoc.isValid()) {
4043 // This is a pack expansion.
4044 if (!BaseType->containsUnexpandedParameterPack()) {
4045 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00004046 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00004047
Douglas Gregor44e7df62011-01-04 00:32:56 +00004048 EllipsisLoc = SourceLocation();
4049 }
4050 } else {
4051 // Check for any unexpanded parameter packs.
4052 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4053 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00004054
Sebastian Redla9351792012-02-11 23:51:47 +00004055 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00004056 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004057 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004058
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004059 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00004060 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4061 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004062 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004063 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4064 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004065 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004066
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004067 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4068 VirtualBaseSpec);
4069
4070 // C++ [base.class.init]p2:
4071 // Unless the mem-initializer-id names a nonstatic data member of the
4072 // constructor's class or a direct or virtual base of that class, the
4073 // mem-initializer is ill-formed.
4074 if (!DirectBaseSpec && !VirtualBaseSpec) {
4075 // If the class has any dependent bases, then it's possible that
4076 // one of those types will resolve to the same type as
4077 // BaseType. Therefore, just treat this as a dependent base
4078 // class initialization. FIXME: Should we try to check the
4079 // initialization anyway? It seems odd.
4080 if (ClassDecl->hasAnyDependentBases())
4081 Dependent = true;
4082 else
4083 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4084 << BaseType << Context.getTypeDeclType(ClassDecl)
4085 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4086 }
4087 }
4088
4089 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004090 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004091
Sebastian Redla74948d2011-09-24 17:48:25 +00004092 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4093 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004094 InitRange.getBegin(), Init,
4095 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004096 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004097
4098 // C++ [base.class.init]p2:
4099 // If a mem-initializer-id is ambiguous because it designates both
4100 // a direct non-virtual base class and an inherited virtual base
4101 // class, the mem-initializer is ill-formed.
4102 if (DirectBaseSpec && VirtualBaseSpec)
4103 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004104 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004105
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004106 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004107 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004108 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004109
4110 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004111 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004112 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004113 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004114 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004115 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004116 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004117
4118 InitializedEntity BaseEntity =
4119 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4120 InitializationKind Kind =
4121 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4122 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4123 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004124 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004126 if (BaseInit.isInvalid())
4127 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004128
Richard Smith945f8d32013-01-14 22:39:08 +00004129 // C++11 [class.base.init]p7:
4130 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004131 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004132 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004133 if (BaseInit.isInvalid())
4134 return true;
4135
4136 // If we are in a dependent context, template instantiation will
4137 // perform this type-checking again. Just save the arguments that we
4138 // received in a ParenListExpr.
4139 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4140 // of the information that we have about the base
4141 // initializer. However, deconstructing the ASTs is a dicey process,
4142 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004143 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004144 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004145
Alexis Hunt1d792652011-01-08 20:30:50 +00004146 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004147 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004148 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004149 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004150 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004151}
4152
Sebastian Redl22653ba2011-08-30 19:58:05 +00004153// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004154static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4155 if (T.isNull()) T = E->getType();
4156 QualType TargetType = SemaRef.BuildReferenceType(
4157 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004158 SourceLocation ExprLoc = E->getLocStart();
4159 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4160 TargetType, ExprLoc);
4161
4162 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4163 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004164 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004165}
4166
Anders Carlsson1b00e242010-04-23 03:10:23 +00004167/// ImplicitInitializerKind - How an implicit base or member initializer should
4168/// initialize its base or member.
4169enum ImplicitInitializerKind {
4170 IIK_Default,
4171 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004172 IIK_Move,
4173 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004174};
4175
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004176static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004177BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004178 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004179 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004180 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004181 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004182 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004183 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4184 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004185
John McCalldadc5752010-08-24 06:29:42 +00004186 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004187
4188 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004189 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004190 case IIK_Default: {
4191 InitializationKind InitKind
4192 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004193 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4194 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004195 break;
4196 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004197
Sebastian Redl22653ba2011-08-30 19:58:05 +00004198 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004199 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004200 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004201 ParmVarDecl *Param = Constructor->getParamDecl(0);
4202 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004203
Anders Carlsson1b00e242010-04-23 03:10:23 +00004204 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004205 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004206 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004207 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004208 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004209
Eli Friedmanfa0df832012-02-02 03:46:19 +00004210 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4211
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004212 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004213 QualType ArgTy =
4214 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4215 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004216
Sebastian Redl22653ba2011-08-30 19:58:05 +00004217 if (Moving) {
4218 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4219 }
4220
John McCallcf142162010-08-07 06:22:56 +00004221 CXXCastPath BasePath;
4222 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004223 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4224 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004225 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004226 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004227
Anders Carlsson1b00e242010-04-23 03:10:23 +00004228 InitializationKind InitKind
4229 = InitializationKind::CreateDirect(Constructor->getLocation(),
4230 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004231 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4232 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004233 break;
4234 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004235 }
John McCallb268a282010-08-23 23:25:46 +00004236
Douglas Gregora40433a2010-12-07 00:41:46 +00004237 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004238 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004239 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004240
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004241 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004242 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004243 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4244 SourceLocation()),
4245 BaseSpec->isVirtual(),
4246 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004247 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004248 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004249 SourceLocation());
4250
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004251 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004252}
4253
Sebastian Redl22653ba2011-08-30 19:58:05 +00004254static bool RefersToRValueRef(Expr *MemRef) {
4255 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4256 return Referenced->getType()->isRValueReferenceType();
4257}
4258
Anders Carlsson3c1db572010-04-23 02:15:47 +00004259static bool
4260BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004261 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004262 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004263 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004264 if (Field->isInvalidDecl())
4265 return true;
4266
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004267 SourceLocation Loc = Constructor->getLocation();
4268
Sebastian Redl22653ba2011-08-30 19:58:05 +00004269 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4270 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004271 ParmVarDecl *Param = Constructor->getParamDecl(0);
4272 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004273
4274 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004275 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4276 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004277
Anders Carlsson423f5d82010-04-23 16:04:08 +00004278 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004279 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004280 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004281 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004282
Eli Friedmanfa0df832012-02-02 03:46:19 +00004283 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4284
Sebastian Redl22653ba2011-08-30 19:58:05 +00004285 if (Moving) {
4286 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4287 }
4288
Douglas Gregor94f9a482010-05-05 05:51:00 +00004289 // Build a reference to this field within the parameter.
4290 CXXScopeSpec SS;
4291 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4292 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004293 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4294 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004295 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004296 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004297 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004298 ParamType, Loc,
4299 /*IsArrow=*/false,
4300 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004301 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004302 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004303 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004304 /*TemplateArgs=*/nullptr,
4305 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004306 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004307 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004308
4309 // C++11 [class.copy]p15:
4310 // - if a member m has rvalue reference type T&&, it is direct-initialized
4311 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004312 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004313 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004314 }
4315
Richard Smith30e304e2016-12-14 00:03:17 +00004316 InitializedEntity Entity =
4317 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4318 /*Implicit*/ true)
4319 : InitializedEntity::InitializeMember(Field, nullptr,
4320 /*Implicit*/ true);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004321
Douglas Gregor94f9a482010-05-05 05:51:00 +00004322 // Direct-initialize to use the copy constructor.
4323 InitializationKind InitKind =
4324 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4325
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004326 Expr *CtorArgE = CtorArg.getAs<Expr>();
Richard Smith30e304e2016-12-14 00:03:17 +00004327 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4328 ExprResult MemberInit =
4329 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004330 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004331 if (MemberInit.isInvalid())
4332 return true;
4333
Richard Smith30e304e2016-12-14 00:03:17 +00004334 if (Indirect)
4335 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4336 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4337 else
4338 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4339 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004340 return false;
4341 }
4342
Richard Smithc2bc61b2013-03-18 21:12:30 +00004343 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4344 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004345
Anders Carlsson3c1db572010-04-23 02:15:47 +00004346 QualType FieldBaseElementType =
4347 SemaRef.Context.getBaseElementType(Field->getType());
4348
Anders Carlsson3c1db572010-04-23 02:15:47 +00004349 if (FieldBaseElementType->isRecordType()) {
Richard Smith30e304e2016-12-14 00:03:17 +00004350 InitializedEntity InitEntity =
4351 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4352 /*Implicit*/ true)
4353 : InitializedEntity::InitializeMember(Field, nullptr,
4354 /*Implicit*/ true);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004355 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004356 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004357
4358 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4359 ExprResult MemberInit =
4360 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004361
Douglas Gregora40433a2010-12-07 00:41:46 +00004362 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004363 if (MemberInit.isInvalid())
4364 return true;
4365
Douglas Gregor493627b2011-08-10 15:22:55 +00004366 if (Indirect)
4367 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4368 Indirect, Loc,
4369 Loc,
4370 MemberInit.get(),
4371 Loc);
4372 else
4373 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4374 Field, Loc, Loc,
4375 MemberInit.get(),
4376 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004377 return false;
4378 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004379
Alexis Hunt8b455182011-05-17 00:19:05 +00004380 if (!Field->getParent()->isUnion()) {
4381 if (FieldBaseElementType->isReferenceType()) {
4382 SemaRef.Diag(Constructor->getLocation(),
4383 diag::err_uninitialized_member_in_ctor)
4384 << (int)Constructor->isImplicit()
4385 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4386 << 0 << Field->getDeclName();
4387 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4388 return true;
4389 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004390
Alexis Hunt8b455182011-05-17 00:19:05 +00004391 if (FieldBaseElementType.isConstQualified()) {
4392 SemaRef.Diag(Constructor->getLocation(),
4393 diag::err_uninitialized_member_in_ctor)
4394 << (int)Constructor->isImplicit()
4395 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4396 << 1 << Field->getDeclName();
4397 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4398 return true;
4399 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004400 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004401
David Blaikiebbafb8a2012-03-11 07:00:24 +00004402 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004403 FieldBaseElementType->isObjCRetainableType() &&
4404 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4405 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004406 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004407 // Default-initialize Objective-C pointers to NULL.
4408 CXXMemberInit
4409 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4410 Loc, Loc,
4411 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4412 Loc);
4413 return false;
4414 }
4415
Anders Carlsson3c1db572010-04-23 02:15:47 +00004416 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004417 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004418 return false;
4419}
John McCallbc83b3f2010-05-20 23:23:51 +00004420
4421namespace {
4422struct BaseAndFieldInfo {
4423 Sema &S;
4424 CXXConstructorDecl *Ctor;
4425 bool AnyErrorsInInits;
4426 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004427 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004428 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004429 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004430
4431 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4432 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004433 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004434 if (Ctor->getInheritedConstructor())
4435 IIK = IIK_Inherit;
4436 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004437 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004438 else if (Generated && Ctor->isMoveConstructor())
4439 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004440 else
4441 IIK = IIK_Default;
4442 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004443
4444 bool isImplicitCopyOrMove() const {
4445 switch (IIK) {
4446 case IIK_Copy:
4447 case IIK_Move:
4448 return true;
4449
4450 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004451 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004452 return false;
4453 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004454
4455 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004456 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004457
4458 bool addFieldInitializer(CXXCtorInitializer *Init) {
4459 AllToInit.push_back(Init);
4460
4461 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004462 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004463 S.UnusedPrivateFields.remove(Init->getAnyMember());
4464
4465 return false;
4466 }
John McCallbc83b3f2010-05-20 23:23:51 +00004467
Richard Smithab44d5b2013-12-10 08:25:00 +00004468 bool isInactiveUnionMember(FieldDecl *Field) {
4469 RecordDecl *Record = Field->getParent();
4470 if (!Record->isUnion())
4471 return false;
4472
Richard Smith8d183852013-12-10 20:56:03 +00004473 if (FieldDecl *Active =
4474 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004475 return Active != Field->getCanonicalDecl();
4476
4477 // In an implicit copy or move constructor, ignore any in-class initializer.
4478 if (isImplicitCopyOrMove())
4479 return true;
4480
4481 // If there's no explicit initialization, the field is active only if it
4482 // has an in-class initializer...
4483 if (Field->hasInClassInitializer())
4484 return false;
4485 // ... or it's an anonymous struct or union whose class has an in-class
4486 // initializer.
4487 if (!Field->isAnonymousStructOrUnion())
4488 return true;
4489 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4490 return !FieldRD->hasInClassInitializer();
4491 }
4492
4493 /// \brief Determine whether the given field is, or is within, a union member
4494 /// that is inactive (because there was an initializer given for a different
4495 /// member of the union, or because the union was not initialized at all).
4496 bool isWithinInactiveUnionMember(FieldDecl *Field,
4497 IndirectFieldDecl *Indirect) {
4498 if (!Indirect)
4499 return isInactiveUnionMember(Field);
4500
Aaron Ballman29c94602014-03-07 18:36:15 +00004501 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004502 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004503 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004504 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004505 }
4506 return false;
4507 }
4508};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004509}
Richard Smithc94ec842011-09-19 13:34:43 +00004510
Douglas Gregor10f939c2011-11-02 23:04:16 +00004511/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4512/// array type.
4513static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4514 if (T->isIncompleteArrayType())
4515 return true;
4516
4517 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4518 if (!ArrayT->getSize())
4519 return true;
4520
4521 T = ArrayT->getElementType();
4522 }
4523
4524 return false;
4525}
4526
Richard Smith938f40b2011-06-11 17:19:42 +00004527static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004528 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004529 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004530 if (Field->isInvalidDecl())
4531 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004532
Chandler Carruth139e9622010-06-30 02:59:29 +00004533 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004534 if (CXXCtorInitializer *Init =
4535 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004536 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004537
Richard Smithab44d5b2013-12-10 08:25:00 +00004538 // C++11 [class.base.init]p8:
4539 // if the entity is a non-static data member that has a
4540 // brace-or-equal-initializer and either
4541 // -- the constructor's class is a union and no other variant member of that
4542 // union is designated by a mem-initializer-id or
4543 // -- the constructor's class is not a union, and, if the entity is a member
4544 // of an anonymous union, no other member of that union is designated by
4545 // a mem-initializer-id,
4546 // the entity is initialized as specified in [dcl.init].
4547 //
4548 // We also apply the same rules to handle anonymous structs within anonymous
4549 // unions.
4550 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4551 return false;
4552
Douglas Gregor7db3e952011-11-28 20:03:15 +00004553 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004554 ExprResult DIE =
4555 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4556 if (DIE.isInvalid())
4557 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004558 CXXCtorInitializer *Init;
4559 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004560 Init = new (SemaRef.Context)
4561 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4562 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004563 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004564 Init = new (SemaRef.Context)
4565 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4566 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004567 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004568 }
4569
Douglas Gregor10f939c2011-11-02 23:04:16 +00004570 // Don't initialize incomplete or zero-length arrays.
4571 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4572 return false;
4573
John McCallbc83b3f2010-05-20 23:23:51 +00004574 // Don't try to build an implicit initializer if there were semantic
4575 // errors in any of the initializers (and therefore we might be
4576 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004577 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004578 return false;
4579
Craig Topperc3ec1492014-05-26 06:22:03 +00004580 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004581 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4582 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004583 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004584
Richard Smith0a8cfc72012-08-07 21:30:42 +00004585 if (!Init)
4586 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004587
Richard Smith0a8cfc72012-08-07 21:30:42 +00004588 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004589}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004590
4591bool
4592Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4593 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004594 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004595 Constructor->setNumCtorInitializers(1);
4596 CXXCtorInitializer **initializer =
4597 new (Context) CXXCtorInitializer*[1];
4598 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4599 Constructor->setCtorInitializers(initializer);
4600
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004601 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004602 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004603 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4604 }
4605
Alexis Hunte2622992011-05-05 00:05:47 +00004606 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004607
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004608 DiagnoseUninitializedFields(*this, Constructor);
4609
Alexis Hunt61bc1732011-05-01 07:04:31 +00004610 return false;
4611}
Douglas Gregor493627b2011-08-10 15:22:55 +00004612
David Blaikie3fc2f912013-01-17 05:26:25 +00004613bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4614 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004615 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004616 // Just store the initializers as written, they will be checked during
4617 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004618 if (!Initializers.empty()) {
4619 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004620 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004621 new (Context) CXXCtorInitializer*[Initializers.size()];
4622 memcpy(baseOrMemberInitializers, Initializers.data(),
4623 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004624 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004625 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004626
4627 // Let template instantiation know whether we had errors.
4628 if (AnyErrors)
4629 Constructor->setInvalidDecl();
4630
Anders Carlssondb0a9652010-04-02 06:26:44 +00004631 return false;
4632 }
4633
John McCallbc83b3f2010-05-20 23:23:51 +00004634 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004635
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004636 // We need to build the initializer AST according to order of construction
4637 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004638 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004639 if (!ClassDecl)
4640 return true;
4641
Eli Friedman9cf6b592009-11-09 19:20:36 +00004642 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004643
David Blaikie3fc2f912013-01-17 05:26:25 +00004644 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004645 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004646
Anders Carlssondb0a9652010-04-02 06:26:44 +00004647 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004648 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004649 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004650 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004651
4652 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004653 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004654 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004655 if (FD && FD->getParent()->isUnion())
4656 Info.ActiveUnionMember.insert(std::make_pair(
4657 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4658 }
4659 } else if (FieldDecl *FD = Member->getMember()) {
4660 if (FD->getParent()->isUnion())
4661 Info.ActiveUnionMember.insert(std::make_pair(
4662 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4663 }
4664 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004665 }
4666
Anders Carlsson43c64af2010-04-21 19:52:01 +00004667 // Keep track of the direct virtual bases.
4668 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004669 for (auto &I : ClassDecl->bases()) {
4670 if (I.isVirtual())
4671 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004672 }
4673
Anders Carlssondb0a9652010-04-02 06:26:44 +00004674 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004675 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004676 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004677 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004678 // [class.base.init]p7, per DR257:
4679 // A mem-initializer where the mem-initializer-id names a virtual base
4680 // class is ignored during execution of a constructor of any class that
4681 // is not the most derived class.
4682 if (ClassDecl->isAbstract()) {
4683 // FIXME: Provide a fixit to remove the base specifier. This requires
4684 // tracking the location of the associated comma for a base specifier.
4685 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004686 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004687 DiagnoseAbstractType(ClassDecl);
4688 }
4689
John McCallbc83b3f2010-05-20 23:23:51 +00004690 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004691 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4692 // [class.base.init]p8, per DR257:
4693 // If a given [...] base class is not named by a mem-initializer-id
4694 // [...] and the entity is not a virtual base class of an abstract
4695 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004696 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004697 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004698 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004699 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004700 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004701 HadError = true;
4702 continue;
4703 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004704
John McCallbc83b3f2010-05-20 23:23:51 +00004705 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004706 }
4707 }
Mike Stump11289f42009-09-09 15:08:12 +00004708
John McCallbc83b3f2010-05-20 23:23:51 +00004709 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004710 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004711 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004712 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004713 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004714
Alexis Hunt1d792652011-01-08 20:30:50 +00004715 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004716 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004717 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004718 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004719 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004720 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004721 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004722 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004723 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004724 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004725 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004726
John McCallbc83b3f2010-05-20 23:23:51 +00004727 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004728 }
4729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
John McCallbc83b3f2010-05-20 23:23:51 +00004731 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004732 for (auto *Mem : ClassDecl->decls()) {
4733 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004734 // C++ [class.bit]p2:
4735 // A declaration for a bit-field that omits the identifier declares an
4736 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4737 // initialized.
4738 if (F->isUnnamedBitfield())
4739 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004740
Sebastian Redl22653ba2011-08-30 19:58:05 +00004741 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004742 // handle anonymous struct/union fields based on their individual
4743 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004744 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004745 continue;
4746
4747 if (CollectFieldInitializer(*this, Info, F))
4748 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004749 continue;
4750 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004751
4752 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004753 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004754 continue;
4755
Aaron Ballman629afae2014-03-07 19:56:05 +00004756 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004757 if (F->getType()->isIncompleteArrayType()) {
4758 assert(ClassDecl->hasFlexibleArrayMember() &&
4759 "Incomplete array type is not valid");
4760 continue;
4761 }
4762
Douglas Gregor493627b2011-08-10 15:22:55 +00004763 // Initialize each field of an anonymous struct individually.
4764 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4765 HadError = true;
4766
4767 continue;
4768 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004769 }
Mike Stump11289f42009-09-09 15:08:12 +00004770
David Blaikie3fc2f912013-01-17 05:26:25 +00004771 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004772 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004773 Constructor->setNumCtorInitializers(NumInitializers);
4774 CXXCtorInitializer **baseOrMemberInitializers =
4775 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004776 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004777 NumInitializers * sizeof(CXXCtorInitializer*));
4778 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004779
John McCalla6309952010-03-16 21:39:52 +00004780 // Constructors implicitly reference the base and member
4781 // destructors.
4782 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4783 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004784 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004785
4786 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004787}
4788
David Blaikieb61b8152013-01-17 08:49:22 +00004789static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004790 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004791 const RecordDecl *RD = RT->getDecl();
4792 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004793 for (auto *Field : RD->fields())
4794 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004795 return;
4796 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004797 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004798 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004799}
4800
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004801static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4802 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004803}
4804
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004805static const void *GetKeyForMember(ASTContext &Context,
4806 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004807 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004808 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004809
Richard Smithcd45dbc2014-04-19 03:48:30 +00004810 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004811}
4812
David Blaikie3fc2f912013-01-17 05:26:25 +00004813static void DiagnoseBaseOrMemInitializerOrder(
4814 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4815 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004816 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004817 return;
Mike Stump11289f42009-09-09 15:08:12 +00004818
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004819 // Don't check initializers order unless the warning is enabled at the
4820 // location of at least one initializer.
4821 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004822 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004823 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004824 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4825 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004826 ShouldCheckOrder = true;
4827 break;
4828 }
4829 }
4830 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004831 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004832
John McCallbb7b6582010-04-10 07:37:23 +00004833 // Build the list of bases and members in the order that they'll
4834 // actually be initialized. The explicit initializers should be in
4835 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004836 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004837
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004838 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4839
John McCallbb7b6582010-04-10 07:37:23 +00004840 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004841 for (const auto &VBase : ClassDecl->vbases())
4842 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004843
John McCallbb7b6582010-04-10 07:37:23 +00004844 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004845 for (const auto &Base : ClassDecl->bases()) {
4846 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004847 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004848 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004849 }
Mike Stump11289f42009-09-09 15:08:12 +00004850
John McCallbb7b6582010-04-10 07:37:23 +00004851 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004852 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004853 if (Field->isUnnamedBitfield())
4854 continue;
4855
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004856 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004857 }
4858
John McCallbb7b6582010-04-10 07:37:23 +00004859 unsigned NumIdealInits = IdealInitKeys.size();
4860 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004861
Craig Topperc3ec1492014-05-26 06:22:03 +00004862 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004863 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004864 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004865 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004866
4867 // Scan forward to try to find this initializer in the idealized
4868 // initializers list.
4869 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4870 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004871 break;
John McCallbb7b6582010-04-10 07:37:23 +00004872
4873 // If we didn't find this initializer, it must be because we
4874 // scanned past it on a previous iteration. That can only
4875 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004876 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004877 Sema::SemaDiagnosticBuilder D =
4878 SemaRef.Diag(PrevInit->getSourceLocation(),
4879 diag::warn_initializer_out_of_order);
4880
Francois Pichetd583da02010-12-04 09:14:42 +00004881 if (PrevInit->isAnyMemberInitializer())
4882 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004883 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004884 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004885
Francois Pichetd583da02010-12-04 09:14:42 +00004886 if (Init->isAnyMemberInitializer())
4887 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004888 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004889 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004890
4891 // Move back to the initializer's location in the ideal list.
4892 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4893 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004894 break;
John McCallbb7b6582010-04-10 07:37:23 +00004895
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004896 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004897 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004898 }
John McCallbb7b6582010-04-10 07:37:23 +00004899
4900 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004901 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004902}
4903
John McCall23eebd92010-04-10 09:28:51 +00004904namespace {
4905bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004906 CXXCtorInitializer *Init,
4907 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004908 if (!PrevInit) {
4909 PrevInit = Init;
4910 return false;
4911 }
4912
Douglas Gregorea306a12013-03-25 23:28:23 +00004913 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004914 S.Diag(Init->getSourceLocation(),
4915 diag::err_multiple_mem_initialization)
4916 << Field->getDeclName()
4917 << Init->getSourceRange();
4918 else {
John McCall424cec92011-01-19 06:33:43 +00004919 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004920 assert(BaseClass && "neither field nor base");
4921 S.Diag(Init->getSourceLocation(),
4922 diag::err_multiple_base_initialization)
4923 << QualType(BaseClass, 0)
4924 << Init->getSourceRange();
4925 }
4926 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4927 << 0 << PrevInit->getSourceRange();
4928
4929 return true;
4930}
4931
Alexis Hunt1d792652011-01-08 20:30:50 +00004932typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004933typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4934
4935bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004936 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004937 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004938 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004939 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004940 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004941
4942 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004943 if (Parent->isUnion()) {
4944 UnionEntry &En = Unions[Parent];
4945 if (En.first && En.first != Child) {
4946 S.Diag(Init->getSourceLocation(),
4947 diag::err_multiple_mem_union_initialization)
4948 << Field->getDeclName()
4949 << Init->getSourceRange();
4950 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4951 << 0 << En.second->getSourceRange();
4952 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004953 }
4954 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004955 En.first = Child;
4956 En.second = Init;
4957 }
David Blaikie0f65d592011-11-17 06:01:57 +00004958 if (!Parent->isAnonymousStructOrUnion())
4959 return false;
John McCall23eebd92010-04-10 09:28:51 +00004960 }
4961
4962 Child = Parent;
4963 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004964 }
John McCall23eebd92010-04-10 09:28:51 +00004965
4966 return false;
4967}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004968}
John McCall23eebd92010-04-10 09:28:51 +00004969
Anders Carlssone857b292010-04-02 03:37:03 +00004970/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004971void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004972 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004973 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004974 bool AnyErrors) {
4975 if (!ConstructorDecl)
4976 return;
4977
4978 AdjustDeclIfTemplate(ConstructorDecl);
4979
4980 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004981 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004982
4983 if (!Constructor) {
4984 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4985 return;
4986 }
4987
John McCall23eebd92010-04-10 09:28:51 +00004988 // Mapping for the duplicate initializers check.
4989 // For member initializers, this is keyed with a FieldDecl*.
4990 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004991 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004992
4993 // Mapping for the inconsistent anonymous-union initializers check.
4994 RedundantUnionMap MemberUnions;
4995
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004996 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004997 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004998 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004999
Abramo Bagnara341d7832010-05-26 18:09:23 +00005000 // Set the source order index.
5001 Init->setSourceOrder(i);
5002
Francois Pichetd583da02010-12-04 09:14:42 +00005003 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005004 const void *Key = GetKeyForMember(Context, Init);
5005 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005006 CheckRedundantUnionInit(*this, Init, MemberUnions))
5007 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005008 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005009 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005010 if (CheckRedundantInit(*this, Init, Members[Key]))
5011 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005012 } else {
5013 assert(Init->isDelegatingInitializer());
5014 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005015 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005016 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005017 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005018 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005019 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005020 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005021 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005022 // Return immediately as the initializer is set.
5023 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005024 }
Anders Carlssone857b292010-04-02 03:37:03 +00005025 }
5026
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005027 if (HadError)
5028 return;
5029
David Blaikie3fc2f912013-01-17 05:26:25 +00005030 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005031
David Blaikie3fc2f912013-01-17 05:26:25 +00005032 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005033
Richard Trieuef64e942013-10-25 00:56:00 +00005034 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005035}
5036
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005037void
John McCalla6309952010-03-16 21:39:52 +00005038Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5039 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005040 // Ignore dependent contexts. Also ignore unions, since their members never
5041 // have destructors implicitly called.
5042 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005043 return;
John McCall1064d7e2010-03-16 05:22:47 +00005044
5045 // FIXME: all the access-control diagnostics are positioned on the
5046 // field/base declaration. That's probably good; that said, the
5047 // user might reasonably want to know why the destructor is being
5048 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005049
Anders Carlssondee9a302009-11-17 04:44:12 +00005050 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005051 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005052 if (Field->isInvalidDecl())
5053 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005054
5055 // Don't destroy incomplete or zero-length arrays.
5056 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5057 continue;
5058
Anders Carlssondee9a302009-11-17 04:44:12 +00005059 QualType FieldType = Context.getBaseElementType(Field->getType());
5060
5061 const RecordType* RT = FieldType->getAs<RecordType>();
5062 if (!RT)
5063 continue;
5064
5065 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005066 if (FieldClassDecl->isInvalidDecl())
5067 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005068 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005069 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005070 // The destructor for an implicit anonymous union member is never invoked.
5071 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5072 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005073
Douglas Gregore71edda2010-07-01 22:47:18 +00005074 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005075 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005076 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005077 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005078 << Field->getDeclName()
5079 << FieldType);
5080
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005081 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005082 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005083 }
5084
Richard Smithdf054d32017-02-25 23:53:05 +00005085 // We only potentially invoke the destructors of potentially constructed
5086 // subobjects.
5087 bool VisitVirtualBases = !ClassDecl->isAbstract();
5088
John McCall1064d7e2010-03-16 05:22:47 +00005089 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5090
Anders Carlssondee9a302009-11-17 04:44:12 +00005091 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005092 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005093 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005094 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005095
5096 // Remember direct virtual bases.
Richard Smithdf054d32017-02-25 23:53:05 +00005097 if (Base.isVirtual()) {
5098 if (!VisitVirtualBases)
5099 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005100 DirectVirtualBases.insert(RT);
Richard Smithdf054d32017-02-25 23:53:05 +00005101 }
Anders Carlssondee9a302009-11-17 04:44:12 +00005102
John McCall1064d7e2010-03-16 05:22:47 +00005103 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005104 // If our base class is invalid, we probably can't get its dtor anyway.
5105 if (BaseClassDecl->isInvalidDecl())
5106 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005107 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005108 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005109
Douglas Gregore71edda2010-07-01 22:47:18 +00005110 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005111 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005112
5113 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005114 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005115 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005116 << Base.getType()
5117 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005118 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005119
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005120 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005121 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005122 }
Richard Smithdf054d32017-02-25 23:53:05 +00005123
5124 if (!VisitVirtualBases)
5125 return;
Anders Carlssondee9a302009-11-17 04:44:12 +00005126
5127 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005128 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005129 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005130 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005131
5132 // Ignore direct virtual bases.
5133 if (DirectVirtualBases.count(RT))
5134 continue;
5135
John McCall1064d7e2010-03-16 05:22:47 +00005136 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005137 // If our base class is invalid, we probably can't get its dtor anyway.
5138 if (BaseClassDecl->isInvalidDecl())
5139 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005140 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005141 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005142
Douglas Gregore71edda2010-07-01 22:47:18 +00005143 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005144 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005145 if (CheckDestructorAccess(
5146 ClassDecl->getLocation(), Dtor,
5147 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005148 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005149 Context.getTypeDeclType(ClassDecl)) ==
5150 AR_accessible) {
5151 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005152 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005153 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005154 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005155 }
John McCall1064d7e2010-03-16 05:22:47 +00005156
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005157 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005158 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005159 }
5160}
5161
John McCall48871652010-08-21 09:40:31 +00005162void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005163 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005164 return;
Mike Stump11289f42009-09-09 15:08:12 +00005165
Mike Stump11289f42009-09-09 15:08:12 +00005166 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005167 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005168 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005169 DiagnoseUninitializedFields(*this, Constructor);
5170 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005171}
5172
Richard Smithdb0ac552015-12-18 22:40:25 +00005173bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005174 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005175 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005176
Richard Smithdb0ac552015-12-18 22:40:25 +00005177 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5178 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005179 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005180
Richard Smithdb0ac552015-12-18 22:40:25 +00005181 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5182 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005183
John McCall02db245d2010-08-18 09:41:07 +00005184 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005185 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005186 // over all the declarations when we have a full definition.
5187 const CXXRecordDecl *Def = RD->getDefinition();
5188 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005189 return false;
5190
Richard Smithdb0ac552015-12-18 22:40:25 +00005191 return RD->isAbstract();
5192}
5193
5194bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5195 TypeDiagnoser &Diagnoser) {
5196 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005198
Richard Smithdb0ac552015-12-18 22:40:25 +00005199 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005200 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005201 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005202 return true;
5203}
5204
5205void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5206 // Check if we've already emitted the list of pure virtual functions
5207 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005209 return;
Mike Stump11289f42009-09-09 15:08:12 +00005210
Richard Smithbc46e432013-07-22 02:56:56 +00005211 // If the diagnostic is suppressed, don't emit the notes. We're only
5212 // going to emit them once, so try to attach them to a diagnostic we're
5213 // actually going to show.
5214 if (Diags.isLastDiagnosticIgnored())
5215 return;
5216
Douglas Gregor4165bd62010-03-23 23:47:56 +00005217 CXXFinalOverriderMap FinalOverriders;
5218 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005219
Anders Carlssona2f74f32010-06-03 01:00:02 +00005220 // Keep a set of seen pure methods so we won't diagnose the same method
5221 // more than once.
5222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5223
Douglas Gregor4165bd62010-03-23 23:47:56 +00005224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5225 MEnd = FinalOverriders.end();
5226 M != MEnd;
5227 ++M) {
5228 for (OverridingMethods::iterator SO = M->second.begin(),
5229 SOEnd = M->second.end();
5230 SO != SOEnd; ++SO) {
5231 // C++ [class.abstract]p4:
5232 // A class is abstract if it contains or inherits at least one
5233 // pure virtual function for which the final overrider is pure
5234 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005235
Douglas Gregor4165bd62010-03-23 23:47:56 +00005236 //
5237 if (SO->second.size() != 1)
5238 continue;
5239
5240 if (!SO->second.front().Method->isPure())
5241 continue;
5242
David Blaikie82e95a32014-11-19 07:49:47 +00005243 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005244 continue;
5245
Douglas Gregor4165bd62010-03-23 23:47:56 +00005246 Diag(SO->second.front().Method->getLocation(),
5247 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005248 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005249 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005250 }
5251
5252 if (!PureVirtualClassDiagSet)
5253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5254 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005255}
5256
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005257namespace {
John McCall02db245d2010-08-18 09:41:07 +00005258struct AbstractUsageInfo {
5259 Sema &S;
5260 CXXRecordDecl *Record;
5261 CanQualType AbstractType;
5262 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005263
John McCall02db245d2010-08-18 09:41:07 +00005264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5265 : S(S), Record(Record),
5266 AbstractType(S.Context.getCanonicalType(
5267 S.Context.getTypeDeclType(Record))),
5268 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005269
John McCall02db245d2010-08-18 09:41:07 +00005270 void DiagnoseAbstractType() {
5271 if (Invalid) return;
5272 S.DiagnoseAbstractType(Record);
5273 Invalid = true;
5274 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005275
John McCall02db245d2010-08-18 09:41:07 +00005276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5277};
5278
5279struct CheckAbstractUsage {
5280 AbstractUsageInfo &Info;
5281 const NamedDecl *Ctx;
5282
5283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5284 : Info(Info), Ctx(Ctx) {}
5285
5286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5287 switch (TL.getTypeLocClass()) {
5288#define ABSTRACT_TYPELOC(CLASS, PARENT)
5289#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005291#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005292 }
John McCall02db245d2010-08-18 09:41:07 +00005293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
John McCall02db245d2010-08-18 09:41:07 +00005295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5298 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005299 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005300
5301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005303 }
John McCall02db245d2010-08-18 09:41:07 +00005304 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005305
John McCall02db245d2010-08-18 09:41:07 +00005306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5307 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
John McCall02db245d2010-08-18 09:41:07 +00005310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5311 // Visit the type parameters from a permissive context.
5312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5313 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5314 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5316 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5317 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005318 }
John McCall02db245d2010-08-18 09:41:07 +00005319 }
Mike Stump11289f42009-09-09 15:08:12 +00005320
John McCall02db245d2010-08-18 09:41:07 +00005321 // Visit pointee types from a permissive context.
5322#define CheckPolymorphic(Type) \
5323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5325 }
5326 CheckPolymorphic(PointerTypeLoc)
5327 CheckPolymorphic(ReferenceTypeLoc)
5328 CheckPolymorphic(MemberPointerTypeLoc)
5329 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005330 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005331
John McCall02db245d2010-08-18 09:41:07 +00005332 /// Handle all the types we haven't given a more specific
5333 /// implementation for above.
5334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5335 // Every other kind of type that we haven't called out already
5336 // that has an inner type is either (1) sugar or (2) contains that
5337 // inner type in some way as a subobject.
5338 if (TypeLoc Next = TL.getNextTypeLoc())
5339 return Visit(Next, Sel);
5340
5341 // If there's no inner type and we're in a permissive context,
5342 // don't diagnose.
5343 if (Sel == Sema::AbstractNone) return;
5344
5345 // Check whether the type matches the abstract type.
5346 QualType T = TL.getType();
5347 if (T->isArrayType()) {
5348 Sel = Sema::AbstractArrayType;
5349 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005350 }
John McCall02db245d2010-08-18 09:41:07 +00005351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5352 if (CT != Info.AbstractType) return;
5353
5354 // It matched; do some magic.
5355 if (Sel == Sema::AbstractArrayType) {
5356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5357 << T << TL.getSourceRange();
5358 } else {
5359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5360 << Sel << T << TL.getSourceRange();
5361 }
5362 Info.DiagnoseAbstractType();
5363 }
5364};
5365
5366void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5367 Sema::AbstractDiagSelID Sel) {
5368 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5369}
5370
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005371}
John McCall02db245d2010-08-18 09:41:07 +00005372
5373/// Check for invalid uses of an abstract type in a method declaration.
5374static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5375 CXXMethodDecl *MD) {
5376 // No need to do the check on definitions, which require that
5377 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005378 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005379 return;
5380
5381 // For safety's sake, just ignore it if we don't have type source
5382 // information. This should never happen for non-implicit methods,
5383 // but...
5384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5386}
5387
5388/// Check for invalid uses of an abstract type within a class definition.
5389static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5390 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005391 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005392 if (D->isImplicit()) continue;
5393
5394 // Methods and method templates.
5395 if (isa<CXXMethodDecl>(D)) {
5396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5397 } else if (isa<FunctionTemplateDecl>(D)) {
5398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5400
5401 // Fields and static variables.
5402 } else if (isa<FieldDecl>(D)) {
5403 FieldDecl *FD = cast<FieldDecl>(D);
5404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5406 } else if (isa<VarDecl>(D)) {
5407 VarDecl *VD = cast<VarDecl>(D);
5408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5410
5411 // Nested classes and class templates.
5412 } else if (isa<CXXRecordDecl>(D)) {
5413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5414 } else if (isa<ClassTemplateDecl>(D)) {
5415 CheckAbstractClassUsage(Info,
5416 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5417 }
5418 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005419}
5420
Hans Wennborg99000c22015-08-15 01:18:16 +00005421static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5422 Attr *ClassAttr = getDLLAttr(Class);
5423 if (!ClassAttr)
5424 return;
5425
5426 assert(ClassAttr->getKind() == attr::DLLExport);
5427
5428 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5429
5430 if (TSK == TSK_ExplicitInstantiationDeclaration)
5431 // Don't go any further if this is just an explicit instantiation
5432 // declaration.
5433 return;
5434
5435 for (Decl *Member : Class->decls()) {
5436 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5437 if (!MD)
5438 continue;
5439
5440 if (Member->getAttr<DLLExportAttr>()) {
5441 if (MD->isUserProvided()) {
5442 // Instantiate non-default class member functions ...
5443
5444 // .. except for certain kinds of template specializations.
5445 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5446 continue;
5447
5448 S.MarkFunctionReferenced(Class->getLocation(), MD);
5449
5450 // The function will be passed to the consumer when its definition is
5451 // encountered.
5452 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5453 MD->isCopyAssignmentOperator() ||
5454 MD->isMoveAssignmentOperator()) {
5455 // Synthesize and instantiate non-trivial implicit methods, explicitly
5456 // defaulted methods, and the copy and move assignment operators. The
5457 // latter are exported even if they are trivial, because the address of
5458 // an operator can be taken and should compare equal accross libraries.
5459 DiagnosticErrorTrap Trap(S.Diags);
5460 S.MarkFunctionReferenced(Class->getLocation(), MD);
5461 if (Trap.hasErrorOccurred()) {
5462 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5463 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5464 break;
5465 }
5466
5467 // There is no later point when we will see the definition of this
5468 // function, so pass it to the consumer now.
5469 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5470 }
5471 }
5472 }
5473}
5474
Reid Kleckner82713bf2017-01-09 17:27:17 +00005475static void checkForMultipleExportedDefaultConstructors(Sema &S,
5476 CXXRecordDecl *Class) {
5477 // Only the MS ABI has default constructor closures, so we don't need to do
5478 // this semantic checking anywhere else.
5479 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5480 return;
5481
Reid Kleckner61195e12017-01-05 01:08:22 +00005482 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5483 for (Decl *Member : Class->decls()) {
5484 // Look for exported default constructors.
5485 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
Reid Kleckner82713bf2017-01-09 17:27:17 +00005486 if (!CD || !CD->isDefaultConstructor())
Reid Kleckner61195e12017-01-05 01:08:22 +00005487 continue;
Reid Kleckner82713bf2017-01-09 17:27:17 +00005488 auto *Attr = CD->getAttr<DLLExportAttr>();
5489 if (!Attr)
5490 continue;
5491
5492 // If the class is non-dependent, mark the default arguments as ODR-used so
5493 // that we can properly codegen the constructor closure.
5494 if (!Class->isDependentContext()) {
5495 for (ParmVarDecl *PD : CD->parameters()) {
5496 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5497 S.DiscardCleanupsInEvaluationContext();
5498 }
5499 }
Reid Kleckner61195e12017-01-05 01:08:22 +00005500
5501 if (LastExportedDefaultCtor) {
5502 S.Diag(LastExportedDefaultCtor->getLocation(),
5503 diag::err_attribute_dll_ambiguous_default_ctor)
5504 << Class;
5505 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5506 << CD->getDeclName();
5507 return;
5508 }
5509 LastExportedDefaultCtor = CD;
5510 }
5511}
5512
Hans Wennborg853ae942014-05-30 16:59:42 +00005513/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005514void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005515 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005516
5517 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005518 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005519 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5520 if (Attr *TemplateAttr =
5521 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005522 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005523 A->setInherited(true);
5524 ClassAttr = A;
5525 }
5526 }
5527 }
5528
Hans Wennborg853ae942014-05-30 16:59:42 +00005529 if (!ClassAttr)
5530 return;
5531
Hans Wennborg8313c762014-11-03 16:09:16 +00005532 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005533 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005534 << Class << ClassAttr;
5535 return;
5536 }
5537
Hans Wennborg17f9b442015-05-27 00:06:45 +00005538 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005539 !ClassAttr->isInherited()) {
5540 // Diagnose dll attributes on members of class with dll attribute.
5541 for (Decl *Member : Class->decls()) {
5542 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5543 continue;
5544 InheritableAttr *MemberAttr = getDLLAttr(Member);
5545 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5546 continue;
5547
Hans Wennborg17f9b442015-05-27 00:06:45 +00005548 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005549 diag::err_attribute_dll_member_of_dll_class)
5550 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005551 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005552 Member->setInvalidDecl();
5553 }
5554 }
5555
5556 if (Class->getDescribedClassTemplate())
5557 // Don't inherit dll attribute until the template is instantiated.
5558 return;
5559
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005560 // The class is either imported or exported.
5561 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005562
Hans Wennborgfd76d912015-01-15 21:18:30 +00005563 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5564
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005565 // Ignore explicit dllexport on explicit class template instantiation declarations.
5566 if (ClassExported && !ClassAttr->isInherited() &&
5567 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005568 Class->dropAttr<DLLExportAttr>();
5569 return;
5570 }
5571
Hans Wennborg853ae942014-05-30 16:59:42 +00005572 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005573 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005574
5575 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5576 // seem to be true in practice?
5577
Hans Wennborg853ae942014-05-30 16:59:42 +00005578 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005579 VarDecl *VD = dyn_cast<VarDecl>(Member);
5580 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5581
5582 // Only methods and static fields inherit the attributes.
5583 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005584 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005585
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005586 if (MD) {
5587 // Don't process deleted methods.
5588 if (MD->isDeleted())
5589 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005590
David Majnemer30f058a2015-05-11 03:00:22 +00005591 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005592 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005593 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5594 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005595 continue;
5596
Dmitry Polukhin41581522016-05-13 09:03:56 +00005597 // MSVC versions before 2015 don't export the move assignment operators
5598 // and move constructor, so don't attempt to import/export them if
5599 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005600 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005601 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005602 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005603 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005604 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005605
5606 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5607 // operator is exported anyway.
5608 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5609 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5610 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005611 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005612 }
5613
Hans Wennborg287231c2015-04-22 04:05:17 +00005614 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5615 continue;
5616
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005617 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005618 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005619 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005620 NewAttr->setInherited(true);
5621 Member->addAttr(NewAttr);
5622 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005623 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005624
5625 if (ClassExported)
5626 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005627}
5628
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005629/// \brief Perform propagation of DLL attributes from a derived class to a
5630/// templated base class for MS compatibility.
5631void Sema::propagateDLLAttrToBaseClassTemplate(
5632 CXXRecordDecl *Class, Attr *ClassAttr,
5633 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5634 if (getDLLAttr(
5635 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5636 // If the base class template has a DLL attribute, don't try to change it.
5637 return;
5638 }
5639
5640 auto TSK = BaseTemplateSpec->getSpecializationKind();
5641 if (!getDLLAttr(BaseTemplateSpec) &&
5642 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5643 TSK == TSK_ImplicitInstantiation)) {
5644 // The template hasn't been instantiated yet (or it has, but only as an
5645 // explicit instantiation declaration or implicit instantiation, which means
5646 // we haven't codegenned any members yet), so propagate the attribute.
5647 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5648 NewAttr->setInherited(true);
5649 BaseTemplateSpec->addAttr(NewAttr);
5650
5651 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5652 // needs to be run again to work see the new attribute. Otherwise this will
5653 // get run whenever the template is instantiated.
5654 if (TSK != TSK_Undeclared)
5655 checkClassLevelDLLAttribute(BaseTemplateSpec);
5656
5657 return;
5658 }
5659
5660 if (getDLLAttr(BaseTemplateSpec)) {
5661 // The template has already been specialized or instantiated with an
5662 // attribute, explicitly or through propagation. We should not try to change
5663 // it.
5664 return;
5665 }
5666
5667 // The template was previously instantiated or explicitly specialized without
5668 // a dll attribute, It's too late for us to add an attribute, so warn that
5669 // this is unsupported.
5670 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5671 << BaseTemplateSpec->isExplicitSpecialization();
5672 Diag(ClassAttr->getLocation(), diag::note_attribute);
5673 if (BaseTemplateSpec->isExplicitSpecialization()) {
5674 Diag(BaseTemplateSpec->getLocation(),
5675 diag::note_template_class_explicit_specialization_was_here)
5676 << BaseTemplateSpec;
5677 } else {
5678 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5679 diag::note_template_class_instantiation_was_here)
5680 << BaseTemplateSpec;
5681 }
5682}
5683
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005684static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5685 SourceLocation DefaultLoc) {
5686 switch (S.getSpecialMember(MD)) {
5687 case Sema::CXXDefaultConstructor:
5688 S.DefineImplicitDefaultConstructor(DefaultLoc,
5689 cast<CXXConstructorDecl>(MD));
5690 break;
5691 case Sema::CXXCopyConstructor:
5692 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5693 break;
5694 case Sema::CXXCopyAssignment:
5695 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5696 break;
5697 case Sema::CXXDestructor:
5698 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5699 break;
5700 case Sema::CXXMoveConstructor:
5701 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5702 break;
5703 case Sema::CXXMoveAssignment:
5704 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5705 break;
5706 case Sema::CXXInvalid:
5707 llvm_unreachable("Invalid special member.");
5708 }
5709}
5710
Douglas Gregorc99f1552009-12-03 18:33:45 +00005711/// \brief Perform semantic checks on a class definition that has been
5712/// completing, introducing implicitly-declared members, checking for
5713/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005714void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005715 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005716 return;
5717
John McCall02db245d2010-08-18 09:41:07 +00005718 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5719 AbstractUsageInfo Info(*this, Record);
5720 CheckAbstractClassUsage(Info, Record);
5721 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005722
5723 // If this is not an aggregate type and has no user-declared constructor,
5724 // complain about any non-static data members of reference or const scalar
5725 // type, since they will never get initializers.
5726 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005727 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5728 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005729 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005730 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005731 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005732 continue;
5733
Douglas Gregor454a5b62010-04-15 00:00:53 +00005734 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005735 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005736 if (!Complained) {
5737 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5738 << Record->getTagKind() << Record;
5739 Complained = true;
5740 }
5741
5742 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5743 << F->getType()->isReferenceType()
5744 << F->getDeclName();
5745 }
5746 }
5747 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005748
Douglas Gregor36c22a22010-10-15 13:21:21 +00005749 if (Record->getIdentifier()) {
5750 // C++ [class.mem]p13:
5751 // If T is the name of a class, then each of the following shall have a
5752 // name different from T:
5753 // - every member of every anonymous union that is a member of class T.
5754 //
5755 // C++ [class.mem]p14:
5756 // In addition, if class T has a user-declared constructor (12.1), every
5757 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005758 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5759 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5760 ++I) {
5761 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005762 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5763 isa<IndirectFieldDecl>(D)) {
5764 Diag(D->getLocation(), diag::err_member_name_of_class)
5765 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005766 break;
5767 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005768 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005769 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005770
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005771 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005772 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005773 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005774 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5775 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005776 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5777 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5778 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005779
David Majnemera5433082013-10-18 00:33:31 +00005780 if (Record->isAbstract()) {
5781 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5782 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5783 << FA->isSpelledAsSealed();
5784 DiagnoseAbstractType(Record);
5785 }
David Blaikie348df502012-09-21 03:21:07 +00005786 }
5787
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005788 bool HasMethodWithOverrideControl = false,
5789 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005790 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005791 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005792 // See if a method overloads virtual methods in a base
5793 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005794 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005795 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005796 if (M->hasAttr<OverrideAttr>())
5797 HasMethodWithOverrideControl = true;
5798 else if (M->size_overridden_methods() > 0)
5799 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005800 // Check whether the explicitly-defaulted special members are valid.
5801 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005802 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005803
5804 // For an explicitly defaulted or deleted special member, we defer
5805 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005806 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005807 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005808 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005809 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005810
5811 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005812 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005813 }
5814 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005815
5816 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5817 M->hasAttr<DLLExportAttr>()) {
5818 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5819 M->isTrivial() &&
5820 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5821 CSM == CXXDestructor))
5822 M->dropAttr<DLLExportAttr>();
5823
5824 if (M->hasAttr<DLLExportAttr>()) {
5825 DefineImplicitSpecialMember(*this, M, M->getLocation());
5826 ActOnFinishInlineFunctionDef(M);
5827 }
5828 }
Richard Smithbd305122012-12-11 01:14:52 +00005829 }
5830 }
5831
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005832 if (HasMethodWithOverrideControl &&
5833 HasOverridingMethodWithoutOverrideControl) {
5834 // At least one method has the 'override' control declared.
5835 // Diagnose all other overridden methods which do not have 'override' specified on them.
5836 for (auto *M : Record->methods())
5837 DiagnoseAbsenceOfOverrideControl(M);
5838 }
Sebastian Redl08905022011-02-05 19:23:19 +00005839
John McCall95833f32014-02-27 20:30:49 +00005840 // ms_struct is a request to use the same ABI rules as MSVC. Check
5841 // whether this class uses any C++ features that are implemented
5842 // completely differently in MSVC, and if so, emit a diagnostic.
5843 // That diagnostic defaults to an error, but we allow projects to
5844 // map it down to a warning (or ignore it). It's a fairly common
5845 // practice among users of the ms_struct pragma to mass-annotate
5846 // headers, sweeping up a bunch of types that the project doesn't
5847 // really rely on MSVC-compatible layout for. We must therefore
5848 // support "ms_struct except for C++ stuff" as a secondary ABI.
5849 if (Record->isMsStruct(Context) &&
5850 (Record->isPolymorphic() || Record->getNumBases())) {
5851 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005852 }
5853
Hans Wennborg17f9b442015-05-27 00:06:45 +00005854 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005855}
5856
Richard Smith41c35d62013-11-27 03:39:20 +00005857/// Look up the special member function that would be called by a special
5858/// member function for a subobject of class type.
5859///
5860/// \param Class The class type of the subobject.
5861/// \param CSM The kind of special member function.
5862/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5863/// \param ConstRHS True if this is a copy operation with a const object
5864/// on its RHS, that is, if the argument to the outer special member
5865/// function is 'const' and this is not a field marked 'mutable'.
Richard Smith8bae1be2017-02-24 02:07:20 +00005866static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
Richard Smith41c35d62013-11-27 03:39:20 +00005867 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5868 unsigned FieldQuals, bool ConstRHS) {
5869 unsigned LHSQuals = 0;
5870 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5871 LHSQuals = FieldQuals;
5872
5873 unsigned RHSQuals = FieldQuals;
5874 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5875 RHSQuals = 0;
5876 else if (ConstRHS)
5877 RHSQuals |= Qualifiers::Const;
5878
5879 return S.LookupSpecialMember(Class, CSM,
5880 RHSQuals & Qualifiers::Const,
5881 RHSQuals & Qualifiers::Volatile,
5882 false,
5883 LHSQuals & Qualifiers::Const,
5884 LHSQuals & Qualifiers::Volatile);
5885}
5886
Richard Smith80a47022016-06-29 01:10:27 +00005887class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005888 Sema &S;
5889 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005890
5891 /// A mapping from the base classes through which the constructor was
5892 /// inherited to the using shadow declaration in that base class (or a null
5893 /// pointer if the constructor was declared in that base class).
5894 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5895 InheritedFromBases;
5896
Richard Smith80a47022016-06-29 01:10:27 +00005897public:
Richard Smith5179eb72016-06-28 19:03:57 +00005898 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5899 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005900 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005901 bool DiagnosedMultipleConstructedBases = false;
5902 CXXRecordDecl *ConstructedBase = nullptr;
5903 UsingDecl *ConstructedBaseUsing = nullptr;
5904
5905 // Find the set of such base class subobjects and check that there's a
5906 // unique constructed subobject.
5907 for (auto *D : Shadow->redecls()) {
5908 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5909 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5910 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5911
5912 InheritedFromBases.insert(
5913 std::make_pair(DNominatedBase->getCanonicalDecl(),
5914 DShadow->getNominatedBaseClassShadowDecl()));
5915 if (DShadow->constructsVirtualBase())
5916 InheritedFromBases.insert(
5917 std::make_pair(DConstructedBase->getCanonicalDecl(),
5918 DShadow->getConstructedBaseClassShadowDecl()));
5919 else
5920 assert(DNominatedBase == DConstructedBase);
5921
5922 // [class.inhctor.init]p2:
5923 // If the constructor was inherited from multiple base class subobjects
5924 // of type B, the program is ill-formed.
5925 if (!ConstructedBase) {
5926 ConstructedBase = DConstructedBase;
5927 ConstructedBaseUsing = D->getUsingDecl();
5928 } else if (ConstructedBase != DConstructedBase &&
5929 !Shadow->isInvalidDecl()) {
5930 if (!DiagnosedMultipleConstructedBases) {
5931 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5932 << Shadow->getTargetDecl();
5933 S.Diag(ConstructedBaseUsing->getLocation(),
5934 diag::note_ambiguous_inherited_constructor_using)
5935 << ConstructedBase;
5936 DiagnosedMultipleConstructedBases = true;
5937 }
5938 S.Diag(D->getUsingDecl()->getLocation(),
5939 diag::note_ambiguous_inherited_constructor_using)
5940 << DConstructedBase;
5941 }
5942 }
5943
5944 if (DiagnosedMultipleConstructedBases)
5945 Shadow->setInvalidDecl();
5946 }
5947
5948 /// Find the constructor to use for inherited construction of a base class,
5949 /// and whether that base class constructor inherits the constructor from a
5950 /// virtual base class (in which case it won't actually invoke it).
5951 std::pair<CXXConstructorDecl *, bool>
5952 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5953 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5954 if (It == InheritedFromBases.end())
5955 return std::make_pair(nullptr, false);
5956
5957 // This is an intermediary class.
5958 if (It->second)
5959 return std::make_pair(
5960 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5961 It->second->constructsVirtualBase());
5962
5963 // This is the base class from which the constructor was inherited.
5964 return std::make_pair(Ctor, false);
5965 }
5966};
Richard Smith5179eb72016-06-28 19:03:57 +00005967
Richard Smithb5800092012-06-10 05:43:50 +00005968/// Is the special member function which would be selected to perform the
5969/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005970static bool
5971specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5972 Sema::CXXSpecialMember CSM, unsigned Quals,
5973 bool ConstRHS,
5974 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005975 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005976 // If we're inheriting a constructor, see if we need to call it for this base
5977 // class.
5978 if (InheritedCtor) {
5979 assert(CSM == Sema::CXXDefaultConstructor);
5980 auto BaseCtor =
5981 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5982 if (BaseCtor)
5983 return BaseCtor->isConstexpr();
5984 }
5985
5986 if (CSM == Sema::CXXDefaultConstructor)
5987 return ClassDecl->hasConstexprDefaultConstructor();
5988
Richard Smith8bae1be2017-02-24 02:07:20 +00005989 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005990 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith8bae1be2017-02-24 02:07:20 +00005991 if (!SMOR.getMethod())
Richard Smithb5800092012-06-10 05:43:50 +00005992 // A constructor we wouldn't select can't be "involved in initializing"
5993 // anything.
5994 return true;
Richard Smith8bae1be2017-02-24 02:07:20 +00005995 return SMOR.getMethod()->isConstexpr();
Richard Smithb5800092012-06-10 05:43:50 +00005996}
5997
5998/// Determine whether the specified special member function would be constexpr
5999/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00006000static bool defaultedSpecialMemberIsConstexpr(
6001 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6002 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00006003 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006004 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00006005 return false;
6006
6007 // C++11 [dcl.constexpr]p4:
6008 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00006009 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00006010 switch (CSM) {
6011 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00006012 if (Inherited)
6013 break;
Richard Smith4086a132012-06-10 07:07:24 +00006014 // Since default constructor lookup is essentially trivial (and cannot
6015 // involve, for instance, template instantiation), we compute whether a
6016 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6017 //
6018 // This is important for performance; we need to know whether the default
6019 // constructor is constexpr to determine whether the type is a literal type.
6020 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6021
Richard Smithb5800092012-06-10 05:43:50 +00006022 case Sema::CXXCopyConstructor:
6023 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00006024 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00006025 break;
6026
6027 case Sema::CXXCopyAssignment:
6028 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006029 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00006030 return false;
6031 // In C++1y, we need to perform overload resolution.
6032 Ctor = false;
6033 break;
6034
Richard Smithb5800092012-06-10 05:43:50 +00006035 case Sema::CXXDestructor:
6036 case Sema::CXXInvalid:
6037 return false;
6038 }
6039
6040 // -- if the class is a non-empty union, or for each non-empty anonymous
6041 // union member of a non-union class, exactly one non-static data member
6042 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00006043 //
6044 // If we squint, this is guaranteed, since exactly one non-static data member
6045 // will be initialized (if the constructor isn't deleted), we just don't know
6046 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006047 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006048 return CSM == Sema::CXXDefaultConstructor
6049 ? ClassDecl->hasInClassInitializer() ||
6050 !ClassDecl->hasVariantMembers()
6051 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006052
6053 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006054 if (Ctor && ClassDecl->getNumVBases())
6055 return false;
6056
6057 // C++1y [class.copy]p26:
6058 // -- [the class] is a literal type, and
6059 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006060 return false;
6061
6062 // -- every constructor involved in initializing [...] base class
6063 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006064 // -- the assignment operator selected to copy/move each direct base
6065 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006066 for (const auto &B : ClassDecl->bases()) {
6067 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006068 if (!BaseType) continue;
6069
6070 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006071 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6072 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006073 return false;
6074 }
6075
6076 // -- every constructor involved in initializing non-static data members
6077 // [...] shall be a constexpr constructor;
6078 // -- every non-static data member and base class sub-object shall be
6079 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006080 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006081 // thereof), the assignment operator selected to copy/move that member is
6082 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006083 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006084 if (F->isInvalidDecl())
6085 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006086 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6087 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006088 QualType BaseType = S.Context.getBaseElementType(F->getType());
6089 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006090 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006091 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6092 BaseType.getCVRQualifiers(),
6093 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006094 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006095 } else if (CSM == Sema::CXXDefaultConstructor) {
6096 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006097 }
6098 }
6099
6100 // All OK, it's constexpr!
6101 return true;
6102}
6103
Richard Smithd3b5c9082012-07-27 04:22:15 +00006104static Sema::ImplicitExceptionSpecification
Richard Smith2246c832017-02-24 01:29:42 +00006105ComputeDefaultedSpecialMemberExceptionSpec(
6106 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6107 Sema::InheritedConstructorInfo *ICI);
6108
6109static Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00006110computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
Richard Smith55118002017-02-24 01:36:58 +00006111 auto CSM = S.getSpecialMember(MD);
6112 if (CSM != Sema::CXXInvalid)
6113 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
Richard Smith2246c832017-02-24 01:29:42 +00006114
6115 auto *CD = cast<CXXConstructorDecl>(MD);
6116 assert(CD->getInheritedConstructor() &&
Richard Smithc2bc61b2013-03-18 21:12:30 +00006117 "only special members have implicit exception specs");
Richard Smith2246c832017-02-24 01:29:42 +00006118 Sema::InheritedConstructorInfo ICI(
6119 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6120 return ComputeDefaultedSpecialMemberExceptionSpec(
6121 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006122}
6123
Reid Kleckner78af0702013-08-27 23:08:25 +00006124static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6125 CXXMethodDecl *MD) {
6126 FunctionProtoType::ExtProtoInfo EPI;
6127
6128 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006129 EPI.ExceptionSpec.Type = EST_Unevaluated;
6130 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006131
6132 // Set the calling convention to the default for C++ instance methods.
6133 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6134 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6135 /*IsCXXMethod=*/true));
6136 return EPI;
6137}
6138
Richard Smithd3b5c9082012-07-27 04:22:15 +00006139void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6140 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6141 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6142 return;
6143
Richard Smith7f782272012-07-30 23:48:14 +00006144 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006145 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6146 auto ESI = IES.getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006147
Richard Smith7f782272012-07-30 23:48:14 +00006148 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006149 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006150
6151 // A user-provided destructor can be defined outside the class. When that
6152 // happens, be sure to update the exception specification on both
6153 // declarations.
6154 const FunctionProtoType *CanonicalFPT =
6155 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6156 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006157 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006158}
6159
Richard Smithb9e90b12012-05-15 04:39:51 +00006160void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6161 CXXRecordDecl *RD = MD->getParent();
6162 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006163
Richard Smithb9e90b12012-05-15 04:39:51 +00006164 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6165 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006166
6167 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006168 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006169 bool First = MD == MD->getCanonicalDecl();
6170
6171 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006172
6173 // C++11 [dcl.fct.def.default]p1:
6174 // A function that is explicitly defaulted shall
6175 // -- be a special member function (checked elsewhere),
6176 // -- have the same type (except for ref-qualifiers, and except that a
6177 // copy operation can take a non-const reference) as an implicit
6178 // declaration, and
6179 // -- not have default arguments.
6180 unsigned ExpectedParams = 1;
6181 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6182 ExpectedParams = 0;
6183 if (MD->getNumParams() != ExpectedParams) {
6184 // This also checks for default arguments: a copy or move constructor with a
6185 // default argument is classified as a default constructor, and assignment
6186 // operations and destructors can't have default arguments.
6187 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6188 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006189 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006190 } else if (MD->isVariadic()) {
6191 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6192 << CSM << MD->getSourceRange();
6193 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006194 }
6195
Richard Smithb9e90b12012-05-15 04:39:51 +00006196 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006197
Richard Smithb5800092012-06-10 05:43:50 +00006198 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006199 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006200 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006201 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006202 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006203
Richard Smithb9e90b12012-05-15 04:39:51 +00006204 QualType ReturnType = Context.VoidTy;
6205 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6206 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006207 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006208 QualType ExpectedReturnType =
6209 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6210 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6211 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6212 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6213 HadError = true;
6214 }
6215
6216 // A defaulted special member cannot have cv-qualifiers.
6217 if (Type->getTypeQuals()) {
6218 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006219 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006220 HadError = true;
6221 }
6222 }
6223
6224 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006225 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006226 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006227 if (ExpectedParams && ArgType->isReferenceType()) {
6228 // Argument must be reference to possibly-const T.
6229 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006230 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006231
6232 if (ReferentType.isVolatileQualified()) {
6233 Diag(MD->getLocation(),
6234 diag::err_defaulted_special_member_volatile_param) << CSM;
6235 HadError = true;
6236 }
6237
Richard Smithb5800092012-06-10 05:43:50 +00006238 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006239 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6240 Diag(MD->getLocation(),
6241 diag::err_defaulted_special_member_copy_const_param)
6242 << (CSM == CXXCopyAssignment);
6243 // FIXME: Explain why this special member can't be const.
6244 } else {
6245 Diag(MD->getLocation(),
6246 diag::err_defaulted_special_member_move_const_param)
6247 << (CSM == CXXMoveAssignment);
6248 }
6249 HadError = true;
6250 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006251 } else if (ExpectedParams) {
6252 // A copy assignment operator can take its argument by value, but a
6253 // defaulted one cannot.
6254 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006255 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006256 HadError = true;
6257 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006258
Richard Smithcc36f692011-12-22 02:22:31 +00006259 // C++11 [dcl.fct.def.default]p2:
6260 // An explicitly-defaulted function may be declared constexpr only if it
6261 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006262 // Do not apply this rule to members of class templates, since core issue 1358
6263 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006264 // functions which cannot be constexpr (for non-constructors in C++11 and for
6265 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006266 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6267 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006268 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006269 : isa<CXXConstructorDecl>(MD)) &&
6270 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006271 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6272 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006273 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006274 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006275 }
Richard Smithbd305122012-12-11 01:14:52 +00006276
Richard Smithcc36f692011-12-22 02:22:31 +00006277 // and may have an explicit exception-specification only if it is compatible
6278 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006279 if (Type->hasExceptionSpec()) {
6280 // Delay the check if this is the first declaration of the special member,
6281 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006282 if (First) {
6283 // If the exception specification needs to be instantiated, do so now,
6284 // before we clobber it with an EST_Unevaluated specification below.
6285 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6286 InstantiateExceptionSpec(MD->getLocStart(), MD);
6287 Type = MD->getType()->getAs<FunctionProtoType>();
6288 }
Richard Smithbd305122012-12-11 01:14:52 +00006289 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006290 } else
Richard Smithbd305122012-12-11 01:14:52 +00006291 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6292 }
Richard Smithcc36f692011-12-22 02:22:31 +00006293
6294 // If a function is explicitly defaulted on its first declaration,
6295 if (First) {
6296 // -- it is implicitly considered to be constexpr if the implicit
6297 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006298 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006299
Richard Smithb9e90b12012-05-15 04:39:51 +00006300 // -- it is implicitly considered to have the same exception-specification
6301 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006302 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006303 EPI.ExceptionSpec.Type = EST_Unevaluated;
6304 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006305 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006306 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006307 ExpectedParams),
6308 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006309 }
6310
Richard Smithb9e90b12012-05-15 04:39:51 +00006311 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006312 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006313 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006314 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006315 // C++11 [dcl.fct.def.default]p4:
6316 // [For a] user-provided explicitly-defaulted function [...] if such a
6317 // function is implicitly defined as deleted, the program is ill-formed.
6318 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006319 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006320 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006321 }
6322 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006323
Richard Smithb9e90b12012-05-15 04:39:51 +00006324 if (HadError)
6325 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006326}
6327
Richard Smithbd305122012-12-11 01:14:52 +00006328/// Check whether the exception specification provided for an
6329/// explicitly-defaulted special member matches the exception specification
6330/// that would have been generated for an implicit special member, per
6331/// C++11 [dcl.fct.def.default]p2.
6332void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6333 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006334 // If the exception specification was explicitly specified but hadn't been
6335 // parsed when the method was defaulted, grab it now.
6336 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6337 SpecifiedType =
6338 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6339
Richard Smithbd305122012-12-11 01:14:52 +00006340 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006341 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6342 /*IsCXXMethod=*/true);
6343 FunctionProtoType::ExtProtoInfo EPI(CC);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006344 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6345 EPI.ExceptionSpec = IES.getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006346 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006347 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006348
6349 // Ensure that it matches.
6350 CheckEquivalentExceptionSpec(
6351 PDiag(diag::err_incorrect_defaulted_exception_spec)
6352 << getSpecialMember(MD), PDiag(),
6353 ImplicitType, SourceLocation(),
6354 SpecifiedType, MD->getLocation());
6355}
6356
Alp Tokerae3a9442013-10-18 05:54:19 +00006357void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006358 decltype(DelayedExceptionSpecChecks) Checks;
6359 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006360
Richard Smith88f45492014-11-22 03:09:05 +00006361 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006362 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6363
6364 // Perform any deferred checking of exception specifications for virtual
6365 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006366 for (auto &Check : Checks)
6367 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006368
6369 // Check that any explicitly-defaulted methods have exception specifications
6370 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006371 for (auto &Spec : Specs)
6372 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006373}
6374
Richard Smithd951a1d2012-02-18 02:02:13 +00006375namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +00006376/// CRTP base class for visiting operations performed by a special member
6377/// function (or inherited constructor).
6378template<typename Derived>
6379struct SpecialMemberVisitor {
Richard Smithd951a1d2012-02-18 02:02:13 +00006380 Sema &S;
6381 CXXMethodDecl *MD;
6382 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006383 Sema::InheritedConstructorInfo *ICI;
Richard Smith8bae1be2017-02-24 02:07:20 +00006384
Richard Smith6f0e63e2017-02-24 21:18:47 +00006385 // Properties of the special member, computed for convenience.
6386 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
Richard Smith8bae1be2017-02-24 02:07:20 +00006387
6388 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6389 Sema::InheritedConstructorInfo *ICI)
6390 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006391 switch (CSM) {
6392 case Sema::CXXDefaultConstructor:
6393 case Sema::CXXCopyConstructor:
6394 case Sema::CXXMoveConstructor:
6395 IsConstructor = true;
6396 break;
6397 case Sema::CXXCopyAssignment:
6398 case Sema::CXXMoveAssignment:
6399 IsAssignment = true;
6400 break;
6401 case Sema::CXXDestructor:
6402 break;
6403 case Sema::CXXInvalid:
6404 llvm_unreachable("invalid special member kind");
6405 }
6406
Richard Smith8bae1be2017-02-24 02:07:20 +00006407 if (MD->getNumParams()) {
6408 if (const ReferenceType *RT =
6409 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6410 ConstArg = RT->getPointeeType().isConstQualified();
6411 }
6412 }
6413
Richard Smith6f0e63e2017-02-24 21:18:47 +00006414 Derived &getDerived() { return static_cast<Derived&>(*this); }
6415
6416 /// Is this a "move" special member?
6417 bool isMove() const {
6418 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6419 }
6420
Richard Smith8bae1be2017-02-24 02:07:20 +00006421 /// Look up the corresponding special member in the given class.
6422 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6423 unsigned Quals, bool IsMutable) {
6424 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6425 ConstArg && !IsMutable);
6426 }
6427
Richard Smith6f0e63e2017-02-24 21:18:47 +00006428 /// Look up the constructor for the specified base class to see if it's
6429 /// overridden due to this being an inherited constructor.
6430 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6431 if (!ICI)
6432 return {};
6433 assert(CSM == Sema::CXXDefaultConstructor);
6434 auto *BaseCtor =
6435 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6436 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6437 return MD;
6438 return {};
6439 }
6440
Richard Smith8bae1be2017-02-24 02:07:20 +00006441 /// A base or member subobject.
6442 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6443
Richard Smith6f0e63e2017-02-24 21:18:47 +00006444 /// Get the location to use for a subobject in diagnostics.
Richard Smith8bae1be2017-02-24 02:07:20 +00006445 static SourceLocation getSubobjectLoc(Subobject Subobj) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006446 // FIXME: For an indirect virtual base, the direct base leading to
6447 // the indirect virtual base would be a more useful choice.
Richard Smith8bae1be2017-02-24 02:07:20 +00006448 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6449 return B->getBaseTypeLoc();
6450 else
6451 return Subobj.get<FieldDecl*>()->getLocation();
6452 }
6453
Richard Smith6f0e63e2017-02-24 21:18:47 +00006454 enum BasesToVisit {
6455 /// Visit all non-virtual (direct) bases.
6456 VisitNonVirtualBases,
6457 /// Visit all direct bases, virtual or not.
6458 VisitDirectBases,
6459 /// Visit all non-virtual bases, and all virtual bases if the class
6460 /// is not abstract.
6461 VisitPotentiallyConstructedBases,
6462 /// Visit all direct or virtual bases.
6463 VisitAllBases
6464 };
6465
6466 // Visit the bases and members of the class.
6467 bool visit(BasesToVisit Bases) {
6468 CXXRecordDecl *RD = MD->getParent();
6469
6470 if (Bases == VisitPotentiallyConstructedBases)
6471 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6472
6473 for (auto &B : RD->bases())
6474 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6475 getDerived().visitBase(&B))
6476 return true;
6477
6478 if (Bases == VisitAllBases)
6479 for (auto &B : RD->vbases())
6480 if (getDerived().visitBase(&B))
6481 return true;
6482
6483 for (auto *F : RD->fields())
6484 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6485 getDerived().visitField(F))
6486 return true;
6487
6488 return false;
6489 }
Richard Smith8bae1be2017-02-24 02:07:20 +00006490};
6491}
6492
6493namespace {
6494struct SpecialMemberDeletionInfo
6495 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
Richard Smith852265f2012-03-30 20:53:28 +00006496 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006497
Richard Smithd951a1d2012-02-18 02:02:13 +00006498 SourceLocation Loc;
6499
6500 bool AllFieldsAreConst;
6501
6502 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006503 Sema::CXXSpecialMember CSM,
6504 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
Richard Smith8bae1be2017-02-24 02:07:20 +00006505 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
Richard Smith6f0e63e2017-02-24 21:18:47 +00006506 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
Richard Smithd951a1d2012-02-18 02:02:13 +00006507
6508 bool inUnion() const { return MD->getParent()->isUnion(); }
6509
Richard Smith80a47022016-06-29 01:10:27 +00006510 Sema::CXXSpecialMember getEffectiveCSM() {
6511 return ICI ? Sema::CXXInvalid : CSM;
6512 }
6513
Richard Smith6f0e63e2017-02-24 21:18:47 +00006514 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6515 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6516
Richard Smith852265f2012-03-30 20:53:28 +00006517 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006518 bool shouldDeleteForField(FieldDecl *FD);
6519 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006520
Richard Smithaf136f82012-07-18 03:51:16 +00006521 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6522 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006523 bool shouldDeleteForSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +00006524 Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006525 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006526
6527 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006528};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006529}
Richard Smithd951a1d2012-02-18 02:02:13 +00006530
John McCalld4274212012-04-09 20:53:23 +00006531/// Is the given special member inaccessible when used on the given
6532/// sub-object.
6533bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6534 CXXMethodDecl *target) {
6535 /// If we're operating on a base class, the object type is the
6536 /// type of this special member.
6537 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006538 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006539 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6540 objectTy = S.Context.getTypeDeclType(MD->getParent());
6541 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6542
6543 // If we're operating on a field, the object type is the type of the field.
6544 } else {
6545 objectTy = S.Context.getTypeDeclType(target->getParent());
6546 }
6547
6548 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6549}
6550
Richard Smith852265f2012-03-30 20:53:28 +00006551/// Check whether we should delete a special member due to the implicit
6552/// definition containing a call to a special member of a subobject.
6553bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +00006554 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006555 bool IsDtorCallInCtor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006556 CXXMethodDecl *Decl = SMOR.getMethod();
Richard Smith852265f2012-03-30 20:53:28 +00006557 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6558
6559 int DiagKind = -1;
6560
Richard Smith8bae1be2017-02-24 02:07:20 +00006561 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
Richard Smith852265f2012-03-30 20:53:28 +00006562 DiagKind = !Decl ? 0 : 1;
Richard Smith8bae1be2017-02-24 02:07:20 +00006563 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith852265f2012-03-30 20:53:28 +00006564 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006565 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006566 DiagKind = 3;
6567 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6568 !Decl->isTrivial()) {
6569 // A member of a union must have a trivial corresponding special member.
6570 // As a weird special case, a destructor call from a union's constructor
6571 // must be accessible and non-deleted, but need not be trivial. Such a
6572 // destructor is never actually called, but is semantically checked as
6573 // if it were.
6574 DiagKind = 4;
6575 }
6576
6577 if (DiagKind == -1)
6578 return false;
6579
6580 if (Diagnose) {
6581 if (Field) {
6582 S.Diag(Field->getLocation(),
6583 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006584 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006585 << Field << DiagKind << IsDtorCallInCtor;
6586 } else {
6587 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6588 S.Diag(Base->getLocStart(),
6589 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006590 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006591 << Base->getType() << DiagKind << IsDtorCallInCtor;
6592 }
6593
6594 if (DiagKind == 1)
6595 S.NoteDeletedFunction(Decl);
6596 // FIXME: Explain inaccessibility if DiagKind == 3.
6597 }
6598
6599 return true;
6600}
6601
Richard Smith921bd202012-02-26 09:11:52 +00006602/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006603/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006604bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006605 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006606 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006607 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006608
6609 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006610 // -- any direct or virtual base class, or non-static data member with no
6611 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006612 // either M has no default constructor or overload resolution as applied
6613 // to M's default constructor results in an ambiguity or in a function
6614 // that is deleted or inaccessible
6615 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6616 // -- a direct or virtual base class B that cannot be copied/moved because
6617 // overload resolution, as applied to B's corresponding special member,
6618 // results in an ambiguity or a function that is deleted or inaccessible
6619 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006620 // C++11 [class.dtor]p5:
6621 // -- any direct or virtual base class [...] has a type with a destructor
6622 // that is deleted or inaccessible
6623 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006624 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006625 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6626 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006627 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006628
Richard Smith852265f2012-03-30 20:53:28 +00006629 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6630 // -- any direct or virtual base class or non-static data member has a
6631 // type with a destructor that is deleted or inaccessible
6632 if (IsConstructor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006633 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith852265f2012-03-30 20:53:28 +00006634 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6635 false, false, false, false, false);
6636 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6637 return true;
6638 }
6639
Richard Smith921bd202012-02-26 09:11:52 +00006640 return false;
6641}
6642
6643/// Check whether we should delete a special member function due to the class
6644/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006645bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006646 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006647 // If program is correct, BaseClass cannot be null, but if it is, the error
6648 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006649 if (!BaseClass)
6650 return false;
6651 // If we have an inheriting constructor, check whether we're calling an
6652 // inherited constructor instead of a default constructor.
Richard Smith6f0e63e2017-02-24 21:18:47 +00006653 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6654 if (auto *BaseCtor = SMOR.getMethod()) {
6655 // Note that we do not check access along this path; other than that,
6656 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6657 // FIXME: Check that the base has a usable destructor! Sink this into
6658 // shouldDeleteForClassSubobject.
6659 if (BaseCtor->isDeleted() && Diagnose) {
6660 S.Diag(Base->getLocStart(),
6661 diag::note_deleted_special_member_class_subobject)
6662 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6663 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6664 S.NoteDeletedFunction(BaseCtor);
Richard Smith80a47022016-06-29 01:10:27 +00006665 }
Richard Smith6f0e63e2017-02-24 21:18:47 +00006666 return BaseCtor->isDeleted();
Richard Smith80a47022016-06-29 01:10:27 +00006667 }
6668 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006669}
6670
6671/// Check whether we should delete a special member function due to the class
6672/// having a particular non-static data member.
6673bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6674 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6675 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6676
6677 if (CSM == Sema::CXXDefaultConstructor) {
6678 // For a default constructor, all references must be initialized in-class
6679 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006680 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6681 if (Diagnose)
6682 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006683 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006684 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006685 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006686 // C++11 [class.ctor]p5: any non-variant non-static data member of
6687 // const-qualified type (or array thereof) with no
6688 // brace-or-equal-initializer does not have a user-provided default
6689 // constructor.
6690 if (!inUnion() && FieldType.isConstQualified() &&
6691 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006692 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6693 if (Diagnose)
6694 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006695 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006696 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006697 }
6698
6699 if (inUnion() && !FieldType.isConstQualified())
6700 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006701 } else if (CSM == Sema::CXXCopyConstructor) {
6702 // For a copy constructor, data members must not be of rvalue reference
6703 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006704 if (FieldType->isRValueReferenceType()) {
6705 if (Diagnose)
6706 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6707 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006708 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006709 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006710 } else if (IsAssignment) {
6711 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006712 if (FieldType->isReferenceType()) {
6713 if (Diagnose)
6714 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006715 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006716 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006717 }
6718 if (!FieldRecord && FieldType.isConstQualified()) {
6719 // C++11 [class.copy]p23:
6720 // -- a non-static data member of const non-class type (or array thereof)
6721 if (Diagnose)
6722 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006723 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006724 return true;
6725 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006726 }
6727
6728 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006729 // Some additional restrictions exist on the variant members.
6730 if (!inUnion() && FieldRecord->isUnion() &&
6731 FieldRecord->isAnonymousStructOrUnion()) {
6732 bool AllVariantFieldsAreConst = true;
6733
Richard Smith5704fe82012-03-29 19:00:10 +00006734 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006735 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006736 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006737
6738 if (!UnionFieldType.isConstQualified())
6739 AllVariantFieldsAreConst = false;
6740
Richard Smith921bd202012-02-26 09:11:52 +00006741 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6742 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006743 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006744 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006745 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006746 }
6747
6748 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006749 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006750 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006751 if (Diagnose)
6752 S.Diag(FieldRecord->getLocation(),
6753 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006754 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006755 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006756 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006757
Richard Smith5704fe82012-03-29 19:00:10 +00006758 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006759 // This is technically non-conformant, but sanity demands it.
6760 return false;
6761 }
6762
Richard Smithaf136f82012-07-18 03:51:16 +00006763 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6764 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006765 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006766 }
6767
6768 return false;
6769}
6770
6771/// C++11 [class.ctor] p5:
6772/// A defaulted default constructor for a class X is defined as deleted if
6773/// X is a union and all of its variant members are of const-qualified type.
6774bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006775 // This is a silly definition, because it gives an empty union a deleted
6776 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006777 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6778 bool AnyFields = false;
6779 for (auto *F : MD->getParent()->fields())
6780 if ((AnyFields = !F->isUnnamedBitfield()))
6781 break;
6782 if (!AnyFields)
6783 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006784 if (Diagnose)
6785 S.Diag(MD->getParent()->getLocation(),
6786 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006787 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006788 return true;
6789 }
6790 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006791}
6792
6793/// Determine whether a defaulted special member function should be defined as
6794/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6795/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006796bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006797 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006798 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006799 if (MD->isInvalidDecl())
6800 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006801 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006802 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006803 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006804 return false;
6805
Richard Smithd951a1d2012-02-18 02:02:13 +00006806 // C++11 [expr.lambda.prim]p19:
6807 // The closure type associated with a lambda-expression has a
6808 // deleted (8.4.3) default constructor and a deleted copy
6809 // assignment operator.
6810 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006811 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6812 if (Diagnose)
6813 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006814 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006815 }
6816
Richard Smith6f1e2c62012-04-02 20:59:25 +00006817 // For an anonymous struct or union, the copy and assignment special members
6818 // will never be used, so skip the check. For an anonymous union declared at
6819 // namespace scope, the constructor and destructor are used.
6820 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6821 RD->isAnonymousStructOrUnion())
6822 return false;
6823
Richard Smith852265f2012-03-30 20:53:28 +00006824 // C++11 [class.copy]p7, p18:
6825 // If the class definition declares a move constructor or move assignment
6826 // operator, an implicitly declared copy constructor or copy assignment
6827 // operator is defined as deleted.
6828 if (MD->isImplicit() &&
6829 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006830 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006831
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006832 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6833 // deletion of the corresponding copy operation, not both copy operations.
6834 // MSVC 2015 has adopted the standards conforming behavior.
6835 bool DeletesOnlyMatchingCopy =
6836 getLangOpts().MSVCCompat &&
6837 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6838
Richard Smith852265f2012-03-30 20:53:28 +00006839 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006840 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006841 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006842
6843 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006844 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006845 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006846 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006847 break;
6848 }
6849 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006850 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006851 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006852 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006853 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006854
6855 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006856 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006857 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006858 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006859 break;
6860 }
6861 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006862 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006863 }
6864
6865 if (UserDeclaredMove) {
6866 Diag(UserDeclaredMove->getLocation(),
6867 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006868 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006869 << UserDeclaredMove->isMoveAssignmentOperator();
6870 return true;
6871 }
6872 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006873
Richard Smith6f1e2c62012-04-02 20:59:25 +00006874 // Do access control from the special member function
6875 ContextRAII MethodContext(*this, MD);
6876
Richard Smith921bd202012-02-26 09:11:52 +00006877 // C++11 [class.dtor]p5:
6878 // -- for a virtual destructor, lookup of the non-array deallocation function
6879 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006880 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006881 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006882 DeclarationName Name =
6883 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6884 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006885 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006886 if (Diagnose)
6887 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006888 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006889 }
Richard Smith921bd202012-02-26 09:11:52 +00006890 }
6891
Richard Smith80a47022016-06-29 01:10:27 +00006892 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006893
Richard Smithd1627032013-07-22 18:06:23 +00006894 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smithdf054d32017-02-25 23:53:05 +00006895 // classes, since we are not going to construct them.
6896 // Per DR1658, do not consider virtual bases of destructors of abstract
6897 // classes either.
6898 // Per DR2180, for assignment operators we only assign (and thus only
6899 // consider) direct bases.
6900 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6901 : SMI.VisitPotentiallyConstructedBases))
Richard Smith6f0e63e2017-02-24 21:18:47 +00006902 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006903
Richard Smithd951a1d2012-02-18 02:02:13 +00006904 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006905 return true;
6906
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006907 if (getLangOpts().CUDA) {
6908 // We should delete the special member in CUDA mode if target inference
6909 // failed.
6910 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6911 Diagnose);
6912 }
6913
Alexis Huntea6f0322011-05-11 22:34:38 +00006914 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006915}
6916
Richard Smith92f241f2012-12-08 02:53:02 +00006917/// Perform lookup for a special member of the specified kind, and determine
6918/// whether it is trivial. If the triviality can be determined without the
6919/// lookup, skip it. This is intended for use when determining whether a
6920/// special member of a containing object is trivial, and thus does not ever
6921/// perform overload resolution for default constructors.
6922///
6923/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6924/// member that was most likely to be intended to be trivial, if any.
6925static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6926 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006927 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006928 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006929 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006930
6931 switch (CSM) {
6932 case Sema::CXXInvalid:
6933 llvm_unreachable("not a special member");
6934
6935 case Sema::CXXDefaultConstructor:
6936 // C++11 [class.ctor]p5:
6937 // A default constructor is trivial if:
6938 // - all the [direct subobjects] have trivial default constructors
6939 //
6940 // Note, no overload resolution is performed in this case.
6941 if (RD->hasTrivialDefaultConstructor())
6942 return true;
6943
6944 if (Selected) {
6945 // If there's a default constructor which could have been trivial, dig it
6946 // out. Otherwise, if there's any user-provided default constructor, point
6947 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006948 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006949 if (RD->needsImplicitDefaultConstructor())
6950 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006951 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006952 if (!CI->isDefaultConstructor())
6953 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006954 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006955 if (!DefCtor->isUserProvided())
6956 break;
6957 }
6958
6959 *Selected = DefCtor;
6960 }
6961
6962 return false;
6963
6964 case Sema::CXXDestructor:
6965 // C++11 [class.dtor]p5:
6966 // A destructor is trivial if:
6967 // - all the direct [subobjects] have trivial destructors
6968 if (RD->hasTrivialDestructor())
6969 return true;
6970
6971 if (Selected) {
6972 if (RD->needsImplicitDestructor())
6973 S.DeclareImplicitDestructor(RD);
6974 *Selected = RD->getDestructor();
6975 }
6976
6977 return false;
6978
6979 case Sema::CXXCopyConstructor:
6980 // C++11 [class.copy]p12:
6981 // A copy constructor is trivial if:
6982 // - the constructor selected to copy each direct [subobject] is trivial
6983 if (RD->hasTrivialCopyConstructor()) {
6984 if (Quals == Qualifiers::Const)
6985 // We must either select the trivial copy constructor or reach an
6986 // ambiguity; no need to actually perform overload resolution.
6987 return true;
6988 } else if (!Selected) {
6989 return false;
6990 }
6991 // In C++98, we are not supposed to perform overload resolution here, but we
6992 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6993 // cases like B as having a non-trivial copy constructor:
6994 // struct A { template<typename T> A(T&); };
6995 // struct B { mutable A a; };
6996 goto NeedOverloadResolution;
6997
6998 case Sema::CXXCopyAssignment:
6999 // C++11 [class.copy]p25:
7000 // A copy assignment operator is trivial if:
7001 // - the assignment operator selected to copy each direct [subobject] is
7002 // trivial
7003 if (RD->hasTrivialCopyAssignment()) {
7004 if (Quals == Qualifiers::Const)
7005 return true;
7006 } else if (!Selected) {
7007 return false;
7008 }
7009 // In C++98, we are not supposed to perform overload resolution here, but we
7010 // treat that as a language defect.
7011 goto NeedOverloadResolution;
7012
7013 case Sema::CXXMoveConstructor:
7014 case Sema::CXXMoveAssignment:
7015 NeedOverloadResolution:
Richard Smith8bae1be2017-02-24 02:07:20 +00007016 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00007017 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00007018
7019 // The standard doesn't describe how to behave if the lookup is ambiguous.
7020 // We treat it as not making the member non-trivial, just like the standard
7021 // mandates for the default constructor. This should rarely matter, because
7022 // the member will also be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +00007023 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith92f241f2012-12-08 02:53:02 +00007024 return true;
7025
Richard Smith8bae1be2017-02-24 02:07:20 +00007026 if (!SMOR.getMethod()) {
7027 assert(SMOR.getKind() ==
Richard Smith92f241f2012-12-08 02:53:02 +00007028 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7029 return false;
7030 }
7031
7032 // We deliberately don't check if we found a deleted special member. We're
7033 // not supposed to!
7034 if (Selected)
Richard Smith8bae1be2017-02-24 02:07:20 +00007035 *Selected = SMOR.getMethod();
7036 return SMOR.getMethod()->isTrivial();
Richard Smith92f241f2012-12-08 02:53:02 +00007037 }
7038
7039 llvm_unreachable("unknown special method kind");
7040}
7041
Benjamin Kramer3e350262013-02-15 12:30:38 +00007042static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007043 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00007044 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007045 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00007046
7047 // Look for constructor templates.
7048 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7049 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7050 if (CXXConstructorDecl *CD =
7051 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7052 return CD;
7053 }
7054
Craig Topperc3ec1492014-05-26 06:22:03 +00007055 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00007056}
7057
7058/// The kind of subobject we are checking for triviality. The values of this
7059/// enumeration are used in diagnostics.
7060enum TrivialSubobjectKind {
7061 /// The subobject is a base class.
7062 TSK_BaseClass,
7063 /// The subobject is a non-static data member.
7064 TSK_Field,
7065 /// The object is actually the complete object.
7066 TSK_CompleteObject
7067};
7068
7069/// Check whether the special member selected for a given type would be trivial.
7070static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00007071 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00007072 Sema::CXXSpecialMember CSM,
7073 TrivialSubobjectKind Kind,
7074 bool Diagnose) {
7075 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7076 if (!SubRD)
7077 return true;
7078
7079 CXXMethodDecl *Selected;
7080 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007081 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00007082 return true;
7083
7084 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00007085 if (ConstRHS)
7086 SubType.addConst();
7087
Richard Smith92f241f2012-12-08 02:53:02 +00007088 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7089 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7090 << Kind << SubType.getUnqualifiedType();
7091 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7092 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7093 } else if (!Selected)
7094 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7095 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7096 else if (Selected->isUserProvided()) {
7097 if (Kind == TSK_CompleteObject)
7098 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7099 << Kind << SubType.getUnqualifiedType() << CSM;
7100 else {
7101 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7102 << Kind << SubType.getUnqualifiedType() << CSM;
7103 S.Diag(Selected->getLocation(), diag::note_declared_at);
7104 }
7105 } else {
7106 if (Kind != TSK_CompleteObject)
7107 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7108 << Kind << SubType.getUnqualifiedType() << CSM;
7109
7110 // Explain why the defaulted or deleted special member isn't trivial.
7111 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7112 }
7113 }
7114
7115 return false;
7116}
7117
7118/// Check whether the members of a class type allow a special member to be
7119/// trivial.
7120static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7121 Sema::CXXSpecialMember CSM,
7122 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007123 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007124 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7125 continue;
7126
7127 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7128
7129 // Pretend anonymous struct or union members are members of this class.
7130 if (FI->isAnonymousStructOrUnion()) {
7131 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7132 CSM, ConstArg, Diagnose))
7133 return false;
7134 continue;
7135 }
7136
7137 // C++11 [class.ctor]p5:
7138 // A default constructor is trivial if [...]
7139 // -- no non-static data member of its class has a
7140 // brace-or-equal-initializer
7141 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7142 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007143 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007144 return false;
7145 }
7146
7147 // Objective C ARC 4.3.5:
7148 // [...] nontrivally ownership-qualified types are [...] not trivially
7149 // default constructible, copy constructible, move constructible, copy
7150 // assignable, move assignable, or destructible [...]
7151 if (S.getLangOpts().ObjCAutoRefCount &&
7152 FieldType.hasNonTrivialObjCLifetime()) {
7153 if (Diagnose)
7154 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7155 << RD << FieldType.getObjCLifetime();
7156 return false;
7157 }
7158
Richard Smith41c35d62013-11-27 03:39:20 +00007159 bool ConstRHS = ConstArg && !FI->isMutable();
7160 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7161 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007162 return false;
7163 }
7164
7165 return true;
7166}
7167
7168/// Diagnose why the specified class does not have a trivial special member of
7169/// the given kind.
7170void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7171 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007172
Richard Smith41c35d62013-11-27 03:39:20 +00007173 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7174 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007175 TSK_CompleteObject, /*Diagnose*/true);
7176}
7177
7178/// Determine whether a defaulted or deleted special member function is trivial,
7179/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7180/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7181bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7182 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007183 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7184
7185 CXXRecordDecl *RD = MD->getParent();
7186
7187 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007188
Richard Smith2002bfe2013-11-04 02:02:27 +00007189 // C++11 [class.copy]p12, p25: [DR1593]
7190 // A [special member] is trivial if [...] its parameter-type-list is
7191 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007192 switch (CSM) {
7193 case CXXDefaultConstructor:
7194 case CXXDestructor:
7195 // Trivial default constructors and destructors cannot have parameters.
7196 break;
7197
7198 case CXXCopyConstructor:
7199 case CXXCopyAssignment: {
7200 // Trivial copy operations always have const, non-volatile parameter types.
7201 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007202 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007203 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7204 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7205 if (Diagnose)
7206 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7207 << Param0->getSourceRange() << Param0->getType()
7208 << Context.getLValueReferenceType(
7209 Context.getRecordType(RD).withConst());
7210 return false;
7211 }
7212 break;
7213 }
7214
7215 case CXXMoveConstructor:
7216 case CXXMoveAssignment: {
7217 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007218 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007219 const RValueReferenceType *RT =
7220 Param0->getType()->getAs<RValueReferenceType>();
7221 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7222 if (Diagnose)
7223 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7224 << Param0->getSourceRange() << Param0->getType()
7225 << Context.getRValueReferenceType(Context.getRecordType(RD));
7226 return false;
7227 }
7228 break;
7229 }
7230
7231 case CXXInvalid:
7232 llvm_unreachable("not a special member");
7233 }
7234
Richard Smith92f241f2012-12-08 02:53:02 +00007235 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7236 if (Diagnose)
7237 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7238 diag::note_nontrivial_default_arg)
7239 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7240 return false;
7241 }
7242 if (MD->isVariadic()) {
7243 if (Diagnose)
7244 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7245 return false;
7246 }
7247
7248 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7249 // A copy/move [constructor or assignment operator] is trivial if
7250 // -- the [member] selected to copy/move each direct base class subobject
7251 // is trivial
7252 //
7253 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7254 // A [default constructor or destructor] is trivial if
7255 // -- all the direct base classes have trivial [default constructors or
7256 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007257 for (const auto &BI : RD->bases())
7258 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007259 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007260 return false;
7261
7262 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7263 // A copy/move [constructor or assignment operator] for a class X is
7264 // trivial if
7265 // -- for each non-static data member of X that is of class type (or array
7266 // thereof), the constructor selected to copy/move that member is
7267 // trivial
7268 //
7269 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7270 // A [default constructor or destructor] is trivial if
7271 // -- for all of the non-static data members of its class that are of class
7272 // type (or array thereof), each such class has a trivial [default
7273 // constructor or destructor]
7274 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7275 return false;
7276
7277 // C++11 [class.dtor]p5:
7278 // A destructor is trivial if [...]
7279 // -- the destructor is not virtual
7280 if (CSM == CXXDestructor && MD->isVirtual()) {
7281 if (Diagnose)
7282 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7283 return false;
7284 }
7285
7286 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7287 // A [special member] for class X is trivial if [...]
7288 // -- class X has no virtual functions and no virtual base classes
7289 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7290 if (!Diagnose)
7291 return false;
7292
7293 if (RD->getNumVBases()) {
7294 // Check for virtual bases. We already know that the corresponding
7295 // member in all bases is trivial, so vbases must all be direct.
7296 CXXBaseSpecifier &BS = *RD->vbases_begin();
7297 assert(BS.isVirtual());
7298 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7299 return false;
7300 }
7301
7302 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007303 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007304 if (MI->isVirtual()) {
7305 SourceLocation MLoc = MI->getLocStart();
7306 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7307 return false;
7308 }
7309 }
7310
7311 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7312 }
7313
7314 // Looks like it's trivial!
7315 return true;
7316}
7317
Benjamin Kramer024e6192011-03-04 13:12:48 +00007318namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007319struct FindHiddenVirtualMethod {
7320 Sema *S;
7321 CXXMethodDecl *Method;
7322 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7323 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007324
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007325private:
7326 /// Check whether any most overriden method from MD in Methods
7327 static bool CheckMostOverridenMethods(
7328 const CXXMethodDecl *MD,
7329 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7330 if (MD->size_overridden_methods() == 0)
7331 return Methods.count(MD->getCanonicalDecl());
7332 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7333 E = MD->end_overridden_methods();
7334 I != E; ++I)
7335 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007336 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007337 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007338 }
7339
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007340public:
7341 /// Member lookup function that determines whether a given C++
7342 /// method overloads virtual methods in a base class without overriding any,
7343 /// to be used with CXXRecordDecl::lookupInBases().
7344 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7345 RecordDecl *BaseRecord =
7346 Specifier->getType()->getAs<RecordType>()->getDecl();
7347
7348 DeclarationName Name = Method->getDeclName();
7349 assert(Name.getNameKind() == DeclarationName::Identifier);
7350
7351 bool foundSameNameMethod = false;
7352 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7353 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7354 Path.Decls = Path.Decls.slice(1)) {
7355 NamedDecl *D = Path.Decls.front();
7356 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7357 MD = MD->getCanonicalDecl();
7358 foundSameNameMethod = true;
7359 // Interested only in hidden virtual methods.
7360 if (!MD->isVirtual())
7361 continue;
7362 // If the method we are checking overrides a method from its base
7363 // don't warn about the other overloaded methods. Clang deviates from
7364 // GCC by only diagnosing overloads of inherited virtual functions that
7365 // do not override any other virtual functions in the base. GCC's
7366 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7367 // function from a base class. These cases may be better served by a
7368 // warning (not specific to virtual functions) on call sites when the
7369 // call would select a different function from the base class, were it
7370 // visible.
7371 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7372 if (!S->IsOverload(Method, MD, false))
7373 return true;
7374 // Collect the overload only if its hidden.
7375 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7376 overloadedMethods.push_back(MD);
7377 }
7378 }
7379
7380 if (foundSameNameMethod)
7381 OverloadedMethods.append(overloadedMethods.begin(),
7382 overloadedMethods.end());
7383 return foundSameNameMethod;
7384 }
7385};
7386} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007387
David Blaikie282c92a2012-10-19 00:53:08 +00007388/// \brief Add the most overriden methods from MD to Methods
7389static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007390 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007391 if (MD->size_overridden_methods() == 0)
7392 Methods.insert(MD->getCanonicalDecl());
7393 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7394 E = MD->end_overridden_methods();
7395 I != E; ++I)
7396 AddMostOverridenMethods(*I, Methods);
7397}
7398
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007399/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007400/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007401void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7402 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007403 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007404 return;
7405
7406 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7407 /*bool RecordPaths=*/false,
7408 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007409 FindHiddenVirtualMethod FHVM;
7410 FHVM.Method = MD;
7411 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007412
7413 // Keep the base methods that were overriden or introduced in the subclass
7414 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007415 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007416 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7417 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7418 NamedDecl *ND = *I;
7419 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007420 ND = shad->getTargetDecl();
7421 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007422 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007423 }
7424
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007425 if (DC->lookupInBases(FHVM, Paths))
7426 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007427}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007428
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007429void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7430 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7431 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7432 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7433 PartialDiagnostic PD = PDiag(
7434 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7435 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7436 Diag(overloadedMD->getLocation(), PD);
7437 }
7438}
7439
7440/// \brief Diagnose methods which overload virtual methods in a base class
7441/// without overriding any.
7442void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7443 if (MD->isInvalidDecl())
7444 return;
7445
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007446 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007447 return;
7448
7449 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7450 FindHiddenVirtualMethods(MD, OverloadedMethods);
7451 if (!OverloadedMethods.empty()) {
7452 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7453 << MD << (OverloadedMethods.size() > 1);
7454
7455 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007456 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007457}
7458
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007459void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007460 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007461 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007462 SourceLocation RBrac,
7463 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007464 if (!TagDecl)
7465 return;
Mike Stump11289f42009-09-09 15:08:12 +00007466
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007467 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007468
Rafael Espindola06e1b132012-07-12 04:32:30 +00007469 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7470 if (l->getKind() != AttributeList::AT_Visibility)
7471 continue;
7472 l->setInvalid();
7473 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7474 l->getName();
7475 }
7476
David Blaikie751c5582011-09-22 02:58:26 +00007477 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007478 // strict aliasing violation!
7479 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007480 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007481
Douglas Gregor0be31a22010-07-02 17:43:08 +00007482 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007483 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007484}
7485
Douglas Gregor05379422008-11-03 17:51:48 +00007486/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7487/// special functions, such as the default constructor, copy
7488/// constructor, or destructor, to the given C++ class (C++
7489/// [special]p1). This routine can only be executed just before the
7490/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007491void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007492 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007493 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007494
Richard Smith5179eb72016-06-28 19:03:57 +00007495 if (ClassDecl->hasInheritedConstructor())
7496 DeclareImplicitDefaultConstructor(ClassDecl);
7497 }
Richard Smith12e79312016-05-13 06:47:56 +00007498
Richard Smitha87b7662016-05-13 18:48:05 +00007499 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007500 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007501
Richard Smith6b02d462012-12-08 08:32:28 +00007502 // If the properties or semantics of the copy constructor couldn't be
7503 // determined while the class was being declared, force a declaration
7504 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007505 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7506 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007507 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007508 // For the MS ABI we need to know whether the copy ctor is deleted. A
7509 // prerequisite for deleting the implicit copy ctor is that the class has a
7510 // move ctor or move assignment that is either user-declared or whose
7511 // semantics are inherited from a subobject. FIXME: We should provide a more
7512 // direct way for CodeGen to ask whether the constructor was deleted.
7513 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7514 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7515 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7516 ClassDecl->hasUserDeclaredMoveAssignment() ||
7517 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7518 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007519 }
7520
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007521 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007522 ++ASTContext::NumImplicitMoveConstructors;
7523
Richard Smith12e79312016-05-13 06:47:56 +00007524 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7525 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007526 DeclareImplicitMoveConstructor(ClassDecl);
7527 }
7528
Richard Smitha87b7662016-05-13 18:48:05 +00007529 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007530 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007531
7532 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007533 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007534 // it shows up in the right place in the vtable and that we diagnose
7535 // problems with the implicit exception specification.
7536 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007537 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7538 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007539 DeclareImplicitCopyAssignment(ClassDecl);
7540 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007541
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007542 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007543 ++ASTContext::NumImplicitMoveAssignmentOperators;
7544
7545 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007546 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007547 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7548 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007549 DeclareImplicitMoveAssignment(ClassDecl);
7550 }
7551
Richard Smitha87b7662016-05-13 18:48:05 +00007552 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007553 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007554
7555 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007556 // have to declare the destructor immediately. This ensures that, e.g., it
7557 // shows up in the right place in the vtable and that we diagnose problems
7558 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007559 if (ClassDecl->isDynamicClass() ||
7560 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007561 DeclareImplicitDestructor(ClassDecl);
7562 }
Douglas Gregor05379422008-11-03 17:51:48 +00007563}
7564
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007565unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007566 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007567 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007568
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007569 // The order of template parameters is not important here. All names
7570 // get added to the same scope.
7571 SmallVector<TemplateParameterList *, 4> ParameterLists;
7572
7573 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7574 D = TD->getTemplatedDecl();
7575
7576 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7577 ParameterLists.push_back(PSD->getTemplateParameters());
7578
7579 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7580 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7581 ParameterLists.push_back(DD->getTemplateParameterList(i));
7582
7583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7584 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7585 ParameterLists.push_back(FTD->getTemplateParameters());
7586 }
7587 }
7588
7589 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7590 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7591 ParameterLists.push_back(TD->getTemplateParameterList(i));
7592
7593 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7594 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7595 ParameterLists.push_back(CTD->getTemplateParameters());
7596 }
7597 }
7598
7599 unsigned Count = 0;
7600 for (TemplateParameterList *Params : ParameterLists) {
7601 if (Params->size() > 0)
7602 // Ignore explicit specializations; they don't contribute to the template
7603 // depth.
7604 ++Count;
7605 for (NamedDecl *Param : *Params) {
7606 if (Param->getDeclName()) {
7607 S->AddDecl(Param);
7608 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007609 }
7610 }
7611 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007612
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007613 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007614}
7615
John McCall48871652010-08-21 09:40:31 +00007616void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007617 if (!RecordD) return;
7618 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007619 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007620 PushDeclContext(S, Record);
7621}
7622
John McCall48871652010-08-21 09:40:31 +00007623void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007624 if (!RecordD) return;
7625 PopDeclContext();
7626}
7627
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007628/// This is used to implement the constant expression evaluation part of the
7629/// attribute enable_if extension. There is nothing in standard C++ which would
7630/// require reentering parameters.
7631void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7632 if (!Param)
7633 return;
7634
7635 S->AddDecl(Param);
7636 if (Param->getDeclName())
7637 IdResolver.AddDecl(Param);
7638}
7639
Douglas Gregor4d87df52008-12-16 21:30:33 +00007640/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7641/// parsing a top-level (non-nested) C++ class, and we are now
7642/// parsing those parts of the given Method declaration that could
7643/// not be parsed earlier (C++ [class.mem]p2), such as default
7644/// arguments. This action should enter the scope of the given
7645/// Method declaration as if we had just parsed the qualified method
7646/// name. However, it should not bring the parameters into scope;
7647/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007648void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007649}
7650
7651/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7652/// C++ method declaration. We're (re-)introducing the given
7653/// function parameter into scope for use in parsing later parts of
7654/// the method declaration. For example, we could see an
7655/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007656void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007657 if (!ParamD)
7658 return;
Mike Stump11289f42009-09-09 15:08:12 +00007659
John McCall48871652010-08-21 09:40:31 +00007660 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007661
7662 // If this parameter has an unparsed default argument, clear it out
7663 // to make way for the parsed default argument.
7664 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007665 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007666
John McCall48871652010-08-21 09:40:31 +00007667 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007668 if (Param->getDeclName())
7669 IdResolver.AddDecl(Param);
7670}
7671
7672/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7673/// processing the delayed method declaration for Method. The method
7674/// declaration is now considered finished. There may be a separate
7675/// ActOnStartOfFunctionDef action later (not necessarily
7676/// immediately!) for this method, if it was also defined inside the
7677/// class body.
John McCall48871652010-08-21 09:40:31 +00007678void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007679 if (!MethodD)
7680 return;
Mike Stump11289f42009-09-09 15:08:12 +00007681
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007682 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007683
John McCall48871652010-08-21 09:40:31 +00007684 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007685
7686 // Now that we have our default arguments, check the constructor
7687 // again. It could produce additional diagnostics or affect whether
7688 // the class has implicitly-declared destructors, among other
7689 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7691 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007692
7693 // Check the default arguments, which we may have added.
7694 if (!Method->isInvalidDecl())
7695 CheckCXXDefaultArguments(Method);
7696}
7697
Douglas Gregor831c93f2008-11-05 20:51:48 +00007698/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007699/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007700/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007701/// emit diagnostics and set the invalid bit to true. In any case, the type
7702/// will be updated to reflect a well-formed type for the constructor and
7703/// returned.
7704QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007705 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007706 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007707
7708 // C++ [class.ctor]p3:
7709 // A constructor shall not be virtual (10.3) or static (9.4). A
7710 // constructor can be invoked for a const, volatile or const
7711 // volatile object. A constructor shall not be declared const,
7712 // volatile, or const volatile (9.3.2).
7713 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007714 if (!D.isInvalidType())
7715 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7716 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7717 << SourceRange(D.getIdentifierLoc());
7718 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007719 }
John McCall8e7d6562010-08-26 03:08:43 +00007720 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007721 if (!D.isInvalidType())
7722 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7723 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7724 << SourceRange(D.getIdentifierLoc());
7725 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007726 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007727 }
Mike Stump11289f42009-09-09 15:08:12 +00007728
David Majnemer03f705f2014-07-08 18:18:04 +00007729 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7730 diagnoseIgnoredQualifiers(
7731 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7732 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7733 D.getDeclSpec().getRestrictSpecLoc(),
7734 D.getDeclSpec().getAtomicSpecLoc());
7735 D.setInvalidType();
7736 }
7737
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007738 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007739 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007740 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007741 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7742 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007743 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007744 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7745 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007746 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007747 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7748 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007749 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007750 }
Mike Stump11289f42009-09-09 15:08:12 +00007751
Douglas Gregordb9d6642011-01-26 05:01:58 +00007752 // C++0x [class.ctor]p4:
7753 // A constructor shall not be declared with a ref-qualifier.
7754 if (FTI.hasRefQualifier()) {
7755 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7756 << FTI.RefQualifierIsLValueRef
7757 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7758 D.setInvalidType();
7759 }
7760
Douglas Gregor831c93f2008-11-05 20:51:48 +00007761 // Rebuild the function type "R" without any type qualifiers (in
7762 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007763 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007764 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007765 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007766 return R;
7767
7768 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7769 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007770 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007771
7772 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007773}
7774
Douglas Gregor4d87df52008-12-16 21:30:33 +00007775/// CheckConstructor - Checks a fully-formed constructor for
7776/// well-formedness, issuing any diagnostics required. Returns true if
7777/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007778void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007779 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007780 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7781 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007782 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007783
7784 // C++ [class.copy]p3:
7785 // A declaration of a constructor for a class X is ill-formed if
7786 // its first parameter is of type (optionally cv-qualified) X and
7787 // either there are no other parameters or else all other
7788 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007789 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007790 ((Constructor->getNumParams() == 1) ||
7791 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007792 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7793 Constructor->getTemplateSpecializationKind()
7794 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007795 QualType ParamType = Constructor->getParamDecl(0)->getType();
7796 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7797 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007798 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007799 const char *ConstRef
7800 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7801 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007802 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007803 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007804
7805 // FIXME: Rather that making the constructor invalid, we should endeavor
7806 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007807 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007808 }
7809 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007810}
7811
John McCalldeb646e2010-08-04 01:04:25 +00007812/// CheckDestructor - Checks a fully-formed destructor definition for
7813/// well-formedness, issuing any diagnostics required. Returns true
7814/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007815bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007816 CXXRecordDecl *RD = Destructor->getParent();
7817
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007818 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007819 SourceLocation Loc;
7820
7821 if (!Destructor->isImplicit())
7822 Loc = Destructor->getLocation();
7823 else
7824 Loc = RD->getLocation();
7825
7826 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007827 if (FunctionDecl *OperatorDelete =
7828 FindDeallocationFunctionForDestructor(Loc, RD)) {
7829 MarkFunctionReferenced(Loc, OperatorDelete);
7830 Destructor->setOperatorDelete(OperatorDelete);
7831 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007832 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007833
7834 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007835}
7836
Douglas Gregor831c93f2008-11-05 20:51:48 +00007837/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7838/// the well-formednes of the destructor declarator @p D with type @p
7839/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007840/// emit diagnostics and set the declarator to invalid. Even if this happens,
7841/// will be updated to reflect a well-formed type for the destructor and
7842/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007843QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007844 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007845 // C++ [class.dtor]p1:
7846 // [...] A typedef-name that names a class is a class-name
7847 // (7.1.3); however, a typedef-name that names a class shall not
7848 // be used as the identifier in the declarator for a destructor
7849 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007850 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007851 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007852 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007853 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007854 else if (const TemplateSpecializationType *TST =
7855 DeclaratorType->getAs<TemplateSpecializationType>())
7856 if (TST->isTypeAlias())
7857 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7858 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007859
7860 // C++ [class.dtor]p2:
7861 // A destructor is used to destroy objects of its class type. A
7862 // destructor takes no parameters, and no return type can be
7863 // specified for it (not even void). The address of a destructor
7864 // shall not be taken. A destructor shall not be static. A
7865 // destructor can be invoked for a const, volatile or const
7866 // volatile object. A destructor shall not be declared const,
7867 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007868 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007869 if (!D.isInvalidType())
7870 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7871 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007872 << SourceRange(D.getIdentifierLoc())
7873 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7874
John McCall8e7d6562010-08-26 03:08:43 +00007875 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007876 }
David Majnemer03f705f2014-07-08 18:18:04 +00007877 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007878 // Destructors don't have return types, but the parser will
7879 // happily parse something like:
7880 //
7881 // class X {
7882 // float ~X();
7883 // };
7884 //
7885 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007886 if (D.getDeclSpec().hasTypeSpecifier())
7887 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7888 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7889 << SourceRange(D.getIdentifierLoc());
7890 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7891 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7892 SourceLocation(),
7893 D.getDeclSpec().getConstSpecLoc(),
7894 D.getDeclSpec().getVolatileSpecLoc(),
7895 D.getDeclSpec().getRestrictSpecLoc(),
7896 D.getDeclSpec().getAtomicSpecLoc());
7897 D.setInvalidType();
7898 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007899 }
Mike Stump11289f42009-09-09 15:08:12 +00007900
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007901 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007902 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007903 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007904 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7905 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007906 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007907 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7908 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007909 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007910 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7911 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007912 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007913 }
7914
Douglas Gregordb9d6642011-01-26 05:01:58 +00007915 // C++0x [class.dtor]p2:
7916 // A destructor shall not be declared with a ref-qualifier.
7917 if (FTI.hasRefQualifier()) {
7918 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7919 << FTI.RefQualifierIsLValueRef
7920 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7921 D.setInvalidType();
7922 }
7923
Douglas Gregor831c93f2008-11-05 20:51:48 +00007924 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007925 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007926 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7927
7928 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007929 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007930 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007931 }
7932
Mike Stump11289f42009-09-09 15:08:12 +00007933 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007934 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007935 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007936 D.setInvalidType();
7937 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007938
7939 // Rebuild the function type "R" without any type qualifiers or
7940 // parameters (in case any of the errors above fired) and with
7941 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007942 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007943 if (!D.isInvalidType())
7944 return R;
7945
Douglas Gregor95755162010-07-01 05:10:53 +00007946 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007947 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7948 EPI.Variadic = false;
7949 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007950 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007951 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007952}
7953
Craig Toppere335f252015-10-04 04:53:55 +00007954static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007955 if (Before.isInvalid())
7956 return;
7957 R.setBegin(Before.getBegin());
7958 if (R.getEnd().isInvalid())
7959 R.setEnd(Before.getEnd());
7960}
7961
Craig Toppere335f252015-10-04 04:53:55 +00007962static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007963 if (After.isInvalid())
7964 return;
7965 if (R.getBegin().isInvalid())
7966 R.setBegin(After.getBegin());
7967 R.setEnd(After.getEnd());
7968}
7969
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007970/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7971/// well-formednes of the conversion function declarator @p D with
7972/// type @p R. If there are any errors in the declarator, this routine
7973/// will emit diagnostics and return true. Otherwise, it will return
7974/// false. Either way, the type @p R will be updated to reflect a
7975/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007976void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007977 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007978 // C++ [class.conv.fct]p1:
7979 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007980 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007981 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007982 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007983 if (!D.isInvalidType())
7984 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007985 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7986 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007987 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007988 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007989 }
John McCall212fa2e2010-04-13 00:04:31 +00007990
Richard Smitha865a162014-12-19 02:07:47 +00007991 TypeSourceInfo *ConvTSI = nullptr;
7992 QualType ConvType =
7993 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007994
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007995 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007996 // Conversion functions don't have return types, but the parser will
7997 // happily parse something like:
7998 //
7999 // class X {
8000 // float operator bool();
8001 // };
8002 //
8003 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00008004 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8005 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8006 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00008007 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008008 }
8009
John McCall212fa2e2010-04-13 00:04:31 +00008010 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8011
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008012 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00008013 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008014 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8015
8016 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00008017 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008018 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00008019 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008020 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008021 D.setInvalidType();
8022 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008023
John McCall212fa2e2010-04-13 00:04:31 +00008024 // Diagnose "&operator bool()" and other such nonsense. This
8025 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00008026 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00008027 bool NeedsTypedef = false;
8028 SourceRange Before, After;
8029
8030 // Walk the chunks and extract information on them for our diagnostic.
8031 bool PastFunctionChunk = false;
8032 for (auto &Chunk : D.type_objects()) {
8033 switch (Chunk.Kind) {
8034 case DeclaratorChunk::Function:
8035 if (!PastFunctionChunk) {
8036 if (Chunk.Fun.HasTrailingReturnType) {
8037 TypeSourceInfo *TRT = nullptr;
8038 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8039 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8040 }
8041 PastFunctionChunk = true;
8042 break;
8043 }
8044 // Fall through.
8045 case DeclaratorChunk::Array:
8046 NeedsTypedef = true;
8047 extendRight(After, Chunk.getSourceRange());
8048 break;
8049
8050 case DeclaratorChunk::Pointer:
8051 case DeclaratorChunk::BlockPointer:
8052 case DeclaratorChunk::Reference:
8053 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00008054 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00008055 extendLeft(Before, Chunk.getSourceRange());
8056 break;
8057
8058 case DeclaratorChunk::Paren:
8059 extendLeft(Before, Chunk.Loc);
8060 extendRight(After, Chunk.EndLoc);
8061 break;
8062 }
8063 }
8064
8065 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8066 After.isValid() ? After.getBegin() :
8067 D.getIdentifierLoc();
8068 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8069 DB << Before << After;
8070
8071 if (!NeedsTypedef) {
8072 DB << /*don't need a typedef*/0;
8073
8074 // If we can provide a correct fix-it hint, do so.
8075 if (After.isInvalid() && ConvTSI) {
8076 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008077 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00008078 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8079 << FixItHint::CreateInsertionFromRange(
8080 InsertLoc, CharSourceRange::getTokenRange(Before))
8081 << FixItHint::CreateRemoval(Before);
8082 }
8083 } else if (!Proto->getReturnType()->isDependentType()) {
8084 DB << /*typedef*/1 << Proto->getReturnType();
8085 } else if (getLangOpts().CPlusPlus11) {
8086 DB << /*alias template*/2 << Proto->getReturnType();
8087 } else {
8088 DB << /*might not be fixable*/3;
8089 }
8090
8091 // Recover by incorporating the other type chunks into the result type.
8092 // Note, this does *not* change the name of the function. This is compatible
8093 // with the GCC extension:
8094 // struct S { &operator int(); } s;
8095 // int &r = s.operator int(); // ok in GCC
8096 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00008097 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00008098 }
8099
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008100 // C++ [class.conv.fct]p4:
8101 // The conversion-type-id shall not represent a function type nor
8102 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008103 if (ConvType->isArrayType()) {
8104 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8105 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008106 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008107 } else if (ConvType->isFunctionType()) {
8108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8109 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008110 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008111 }
8112
8113 // Rebuild the function type "R" without any parameters (in case any
8114 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00008115 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00008116 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008117 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008118
Douglas Gregor5fb53972009-01-14 15:45:31 +00008119 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00008120 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008121 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008122 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008123 diag::warn_cxx98_compat_explicit_conversion_functions :
8124 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008125 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008126}
8127
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008128/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8129/// the declaration of the given C++ conversion function. This routine
8130/// is responsible for recording the conversion function in the C++
8131/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008132Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008133 assert(Conversion && "Expected to receive a conversion function declaration");
8134
Douglas Gregor4287b372008-12-12 08:25:50 +00008135 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008136
8137 // Make sure we aren't redeclaring the conversion function.
8138 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008139
8140 // C++ [class.conv.fct]p1:
8141 // [...] A conversion function is never used to convert a
8142 // (possibly cv-qualified) object to the (possibly cv-qualified)
8143 // same object type (or a reference to it), to a (possibly
8144 // cv-qualified) base class of that type (or a reference to it),
8145 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008146 // FIXME: Suppress this warning if the conversion function ends up being a
8147 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008148 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008150 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008151 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008152 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8153 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008154 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008155 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008156 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8157 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008158 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008159 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008160 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008161 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008162 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008163 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008164 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008165 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008166 }
8167
Douglas Gregor457104e2010-09-29 04:25:11 +00008168 if (FunctionTemplateDecl *ConversionTemplate
8169 = Conversion->getDescribedFunctionTemplate())
8170 return ConversionTemplate;
8171
John McCall48871652010-08-21 09:40:31 +00008172 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008173}
8174
Richard Smithf283fdc2017-02-08 00:35:25 +00008175namespace {
8176/// Utility class to accumulate and print a diagnostic listing the invalid
8177/// specifier(s) on a declaration.
8178struct BadSpecifierDiagnoser {
8179 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8180 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8181 ~BadSpecifierDiagnoser() {
8182 Diagnostic << Specifiers;
8183 }
8184
8185 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8186 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8187 }
8188 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8189 return check(SpecLoc,
8190 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8191 }
8192 void check(SourceLocation SpecLoc, const char *Spec) {
8193 if (SpecLoc.isInvalid()) return;
8194 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8195 if (!Specifiers.empty()) Specifiers += " ";
8196 Specifiers += Spec;
8197 }
8198
8199 Sema &S;
8200 Sema::SemaDiagnosticBuilder Diagnostic;
8201 std::string Specifiers;
8202};
8203}
8204
Richard Smith35845152017-02-07 01:37:30 +00008205/// Check the validity of a declarator that we parsed for a deduction-guide.
8206/// These aren't actually declarators in the grammar, so we need to check that
8207/// the user didn't specify any pieces that are not part of the deduction-guide
8208/// grammar.
8209void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8210 StorageClass &SC) {
Richard Smith278890f2017-02-10 20:39:58 +00008211 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8212 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8213 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8214
8215 // C++ [temp.deduct.guide]p3:
8216 // A deduction-gide shall be declared in the same scope as the
8217 // corresponding class template.
8218 if (!CurContext->getRedeclContext()->Equals(
8219 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8220 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8221 << GuidedTemplateDecl;
8222 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8223 }
8224
Richard Smithf283fdc2017-02-08 00:35:25 +00008225 auto &DS = D.getMutableDeclSpec();
8226 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8227 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8228 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8229 DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8230 DS.isConceptSpecified()) {
8231 BadSpecifierDiagnoser Diagnoser(
8232 *this, D.getIdentifierLoc(),
8233 diag::err_deduction_guide_invalid_specifier);
8234
8235 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8236 DS.ClearStorageClassSpecs();
8237 SC = SC_None;
8238
8239 // 'explicit' is permitted.
8240 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8241 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8242 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8243 Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8244 DS.ClearConstexprSpec();
8245 DS.ClearConceptSpec();
8246
8247 Diagnoser.check(DS.getConstSpecLoc(), "const");
8248 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8249 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8250 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8251 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8252 DS.ClearTypeQualifiers();
8253
8254 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8255 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8256 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8257 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8258 DS.ClearTypeSpecType();
8259 }
8260
8261 if (D.isInvalidType())
8262 return;
8263
8264 // Check the declarator is simple enough.
8265 bool FoundFunction = false;
8266 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8267 if (Chunk.Kind == DeclaratorChunk::Paren)
8268 continue;
8269 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8270 Diag(D.getDeclSpec().getLocStart(),
8271 diag::err_deduction_guide_with_complex_decl)
8272 << D.getSourceRange();
8273 break;
8274 }
8275 if (!Chunk.Fun.hasTrailingReturnType()) {
8276 Diag(D.getName().getLocStart(),
8277 diag::err_deduction_guide_no_trailing_return_type);
8278 break;
8279 }
Richard Smith3817e4a2017-02-10 19:49:50 +00008280
8281 // Check that the return type is written as a specialization of
8282 // the template specified as the deduction-guide's name.
8283 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
Richard Smith3817e4a2017-02-10 19:49:50 +00008284 TypeSourceInfo *TSI = nullptr;
8285 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8286 assert(TSI && "deduction guide has valid type but invalid return type?");
8287 bool AcceptableReturnType = false;
8288 bool MightInstantiateToSpecialization = false;
8289 if (auto RetTST =
8290 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8291 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8292 bool TemplateMatches =
8293 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8294 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8295 AcceptableReturnType = true;
8296 else {
8297 // This could still instantiate to the right type, unless we know it
8298 // names the wrong class template.
8299 auto *TD = SpecifiedName.getAsTemplateDecl();
8300 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8301 !TemplateMatches);
8302 }
8303 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8304 MightInstantiateToSpecialization = true;
8305 }
8306
8307 if (!AcceptableReturnType) {
8308 Diag(TSI->getTypeLoc().getLocStart(),
8309 diag::err_deduction_guide_bad_trailing_return_type)
8310 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8311 << TSI->getTypeLoc().getSourceRange();
8312 }
8313
8314 // Keep going to check that we don't have any inner declarator pieces (we
8315 // could still have a function returning a pointer to a function).
Richard Smithf283fdc2017-02-08 00:35:25 +00008316 FoundFunction = true;
8317 }
8318
Richard Smithc88aa3f2017-02-08 01:27:29 +00008319 if (D.isFunctionDefinition())
8320 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
Richard Smith35845152017-02-07 01:37:30 +00008321}
8322
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008323//===----------------------------------------------------------------------===//
8324// Namespace Handling
8325//===----------------------------------------------------------------------===//
8326
Richard Smith45bb8852012-10-04 22:13:39 +00008327/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8328/// reopened.
8329static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8330 SourceLocation Loc,
8331 IdentifierInfo *II, bool *IsInline,
8332 NamespaceDecl *PrevNS) {
8333 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008334
Richard Smithf501cc32012-10-05 01:46:25 +00008335 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8336 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8337 // inline namespaces, with the intention of bringing names into namespace std.
8338 //
8339 // We support this just well enough to get that case working; this is not
8340 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008341 if (*IsInline && II && II->getName().startswith("__atomic") &&
8342 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008343 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008344 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8345 NS = NS->getPreviousDecl())
8346 NS->setInline(*IsInline);
8347 // Patch up the lookup table for the containing namespace. This isn't really
8348 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008349 for (auto *I : PrevNS->decls())
8350 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008351 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8352 return;
8353 }
8354
8355 if (PrevNS->isInline())
8356 // The user probably just forgot the 'inline', so suggest that it
8357 // be added back.
8358 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8359 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8360 else
Richard Smith360cb252016-09-30 23:16:08 +00008361 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008362
8363 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8364 *IsInline = PrevNS->isInline();
8365}
John McCallb1be5232010-08-26 09:15:37 +00008366
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008367/// ActOnStartNamespaceDef - This is called at the start of a namespace
8368/// definition.
John McCall48871652010-08-21 09:40:31 +00008369Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008370 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008371 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008372 SourceLocation IdentLoc,
8373 IdentifierInfo *II,
8374 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008375 AttributeList *AttrList,
8376 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008377 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8378 // For anonymous namespace, take the location of the left brace.
8379 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008380 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008381 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008382 bool IsStd = false;
8383 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008384 Scope *DeclRegionScope = NamespcScope->getParent();
8385
Craig Topperc3ec1492014-05-26 06:22:03 +00008386 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008387 if (II) {
8388 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008389 // The identifier in an original-namespace-definition shall not
8390 // have been previously defined in the declarative region in
8391 // which the original-namespace-definition appears. The
8392 // identifier in an original-namespace-definition is the name of
8393 // the namespace. Subsequently in that declarative region, it is
8394 // treated as an original-namespace-name.
8395 //
8396 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008397 // look through using directives, just look for any ordinary names
8398 // as if by qualified name lookup.
8399 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8400 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008401 NamedDecl *PrevDecl =
8402 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008403 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008404
Douglas Gregore57e7522012-01-07 09:11:48 +00008405 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008406 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008407 if (IsInline != PrevNS->isInline())
8408 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8409 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008410 } else if (PrevDecl) {
8411 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008412 Diag(Loc, diag::err_redefinition_different_kind)
8413 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008414 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008415 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008416 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008417 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008418 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008419 // This is the first "real" definition of the namespace "std", so update
8420 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008421 PrevNS = getStdNamespace();
8422 IsStd = true;
8423 AddToKnown = !IsInline;
8424 } else {
8425 // We've seen this namespace for the first time.
8426 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008427 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008428 } else {
John McCall4fa53422009-10-01 00:25:31 +00008429 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008430
8431 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008432 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008433 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008434 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008435 } else {
8436 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008437 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008438 }
8439
Richard Smith45bb8852012-10-04 22:13:39 +00008440 if (PrevNS && IsInline != PrevNS->isInline())
8441 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8442 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008443 }
8444
8445 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8446 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008447 if (IsInvalid)
8448 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008449
8450 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008451
Douglas Gregore57e7522012-01-07 09:11:48 +00008452 // FIXME: Should we be merging attributes?
8453 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008454 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008455
8456 if (IsStd)
8457 StdNamespace = Namespc;
8458 if (AddToKnown)
8459 KnownNamespaces[Namespc] = false;
8460
8461 if (II) {
8462 PushOnScopeChains(Namespc, DeclRegionScope);
8463 } else {
8464 // Link the anonymous namespace into its parent.
8465 DeclContext *Parent = CurContext->getRedeclContext();
8466 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8467 TU->setAnonymousNamespace(Namespc);
8468 } else {
8469 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008470 }
John McCall4fa53422009-10-01 00:25:31 +00008471
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008472 CurContext->addDecl(Namespc);
8473
John McCall4fa53422009-10-01 00:25:31 +00008474 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8475 // behaves as if it were replaced by
8476 // namespace unique { /* empty body */ }
8477 // using namespace unique;
8478 // namespace unique { namespace-body }
8479 // where all occurrences of 'unique' in a translation unit are
8480 // replaced by the same identifier and this identifier differs
8481 // from all other identifiers in the entire program.
8482
8483 // We just create the namespace with an empty name and then add an
8484 // implicit using declaration, just like the standard suggests.
8485 //
8486 // CodeGen enforces the "universally unique" aspect by giving all
8487 // declarations semantically contained within an anonymous
8488 // namespace internal linkage.
8489
Douglas Gregore57e7522012-01-07 09:11:48 +00008490 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008491 UD = UsingDirectiveDecl::Create(Context, Parent,
8492 /* 'using' */ LBrace,
8493 /* 'namespace' */ SourceLocation(),
8494 /* qualifier */ NestedNameSpecifierLoc(),
8495 /* identifier */ SourceLocation(),
8496 Namespc,
8497 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008498 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008499 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008500 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008501 }
8502
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008503 ActOnDocumentableDecl(Namespc);
8504
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008505 // Although we could have an invalid decl (i.e. the namespace name is a
8506 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008507 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8508 // for the namespace has the declarations that showed up in that particular
8509 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008510 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008511 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008512}
8513
Sebastian Redla6602e92009-11-23 15:34:23 +00008514/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8515/// is a namespace alias, returns the namespace it points to.
8516static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8517 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8518 return AD->getNamespace();
8519 return dyn_cast_or_null<NamespaceDecl>(D);
8520}
8521
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008522/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8523/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008524void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008525 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8526 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008527 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008528 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008529 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008530 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008531}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008532
John McCall28a0cf72010-08-25 07:42:41 +00008533CXXRecordDecl *Sema::getStdBadAlloc() const {
8534 return cast_or_null<CXXRecordDecl>(
8535 StdBadAlloc.get(Context.getExternalSource()));
8536}
8537
Richard Smith96269c52016-09-29 22:49:46 +00008538EnumDecl *Sema::getStdAlignValT() const {
8539 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8540}
8541
John McCall28a0cf72010-08-25 07:42:41 +00008542NamespaceDecl *Sema::getStdNamespace() const {
8543 return cast_or_null<NamespaceDecl>(
8544 StdNamespace.get(Context.getExternalSource()));
8545}
8546
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008547NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8548 if (!StdExperimentalNamespaceCache) {
8549 if (auto Std = getStdNamespace()) {
8550 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8551 SourceLocation(), LookupNamespaceName);
8552 if (!LookupQualifiedName(Result, Std) ||
8553 !(StdExperimentalNamespaceCache =
8554 Result.getAsSingle<NamespaceDecl>()))
8555 Result.suppressDiagnostics();
8556 }
8557 }
8558 return StdExperimentalNamespaceCache;
8559}
8560
Douglas Gregorcdf87022010-06-29 17:53:46 +00008561/// \brief Retrieve the special "std" namespace, which may require us to
8562/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008563NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008564 if (!StdNamespace) {
8565 // The "std" namespace has not yet been defined, so build one implicitly.
8566 StdNamespace = NamespaceDecl::Create(Context,
8567 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008568 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008569 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008570 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008571 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008572 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008573 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008574
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008575 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008576}
8577
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008578bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008579 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008580 "Looking for std::initializer_list outside of C++.");
8581
8582 // We're looking for implicit instantiations of
8583 // template <typename E> class std::initializer_list.
8584
8585 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8586 return false;
8587
Craig Topperc3ec1492014-05-26 06:22:03 +00008588 ClassTemplateDecl *Template = nullptr;
8589 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008590
Sebastian Redl43144e72012-01-17 22:49:58 +00008591 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008592
Sebastian Redl43144e72012-01-17 22:49:58 +00008593 ClassTemplateSpecializationDecl *Specialization =
8594 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8595 if (!Specialization)
8596 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008597
Sebastian Redl43144e72012-01-17 22:49:58 +00008598 Template = Specialization->getSpecializedTemplate();
8599 Arguments = Specialization->getTemplateArgs().data();
8600 } else if (const TemplateSpecializationType *TST =
8601 Ty->getAs<TemplateSpecializationType>()) {
8602 Template = dyn_cast_or_null<ClassTemplateDecl>(
8603 TST->getTemplateName().getAsTemplateDecl());
8604 Arguments = TST->getArgs();
8605 }
8606 if (!Template)
8607 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008608
8609 if (!StdInitializerList) {
8610 // Haven't recognized std::initializer_list yet, maybe this is it.
8611 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8612 if (TemplateClass->getIdentifier() !=
8613 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008614 !getStdNamespace()->InEnclosingNamespaceSetOf(
8615 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008616 return false;
8617 // This is a template called std::initializer_list, but is it the right
8618 // template?
8619 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008620 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008621 return false;
8622 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8623 return false;
8624
8625 // It's the right template.
8626 StdInitializerList = Template;
8627 }
8628
Richard Smith7d7dee72015-02-24 03:30:14 +00008629 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008630 return false;
8631
8632 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008633 if (Element)
8634 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008635 return true;
8636}
8637
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008638static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8639 NamespaceDecl *Std = S.getStdNamespace();
8640 if (!Std) {
8641 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008642 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008643 }
8644
8645 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8646 Loc, Sema::LookupOrdinaryName);
8647 if (!S.LookupQualifiedName(Result, Std)) {
8648 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008649 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008650 }
8651 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8652 if (!Template) {
8653 Result.suppressDiagnostics();
8654 // We found something weird. Complain about the first thing we found.
8655 NamedDecl *Found = *Result.begin();
8656 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008657 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008658 }
8659
8660 // We found some template called std::initializer_list. Now verify that it's
8661 // correct.
8662 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008663 if (Params->getMinRequiredArguments() != 1 ||
8664 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008665 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008666 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008667 }
8668
8669 return Template;
8670}
8671
8672QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8673 if (!StdInitializerList) {
8674 StdInitializerList = LookupStdInitializerList(*this, Loc);
8675 if (!StdInitializerList)
8676 return QualType();
8677 }
8678
8679 TemplateArgumentListInfo Args(Loc, Loc);
8680 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8681 Context.getTrivialTypeSourceInfo(Element,
8682 Loc)));
8683 return Context.getCanonicalType(
8684 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8685}
8686
Richard Smith60437622017-02-09 19:17:44 +00008687bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008688 // C++ [dcl.init.list]p2:
8689 // A constructor is an initializer-list constructor if its first parameter
8690 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8691 // std::initializer_list<E> for some type E, and either there are no other
8692 // parameters or else all other parameters have default arguments.
8693 if (Ctor->getNumParams() < 1 ||
8694 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8695 return false;
8696
8697 QualType ArgType = Ctor->getParamDecl(0)->getType();
8698 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8699 ArgType = RT->getPointeeType().getUnqualifiedType();
8700
Craig Topperc3ec1492014-05-26 06:22:03 +00008701 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008702}
8703
Douglas Gregora172e082011-03-26 22:25:30 +00008704/// \brief Determine whether a using statement is in a context where it will be
8705/// apply in all contexts.
8706static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8707 switch (CurContext->getDeclKind()) {
8708 case Decl::TranslationUnit:
8709 return true;
8710 case Decl::LinkageSpec:
8711 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8712 default:
8713 return false;
8714 }
8715}
8716
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008717namespace {
8718
8719// Callback to only accept typo corrections that are namespaces.
8720class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008721public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008722 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008723 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008724 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008725 return false;
8726 }
8727};
8728
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008729}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008730
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008731static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8732 CXXScopeSpec &SS,
8733 SourceLocation IdentLoc,
8734 IdentifierInfo *Ident) {
8735 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008736 if (TypoCorrection Corrected =
8737 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8738 llvm::make_unique<NamespaceValidatorCCC>(),
8739 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008740 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008741 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8742 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008743 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008744 S.diagnoseTypo(Corrected,
8745 S.PDiag(diag::err_using_directive_member_suggest)
8746 << Ident << DC << DroppedSpecifier << SS.getRange(),
8747 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008748 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008749 S.diagnoseTypo(Corrected,
8750 S.PDiag(diag::err_using_directive_suggest) << Ident,
8751 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008752 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008753 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008754 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008755 }
8756 return false;
8757}
8758
John McCall48871652010-08-21 09:40:31 +00008759Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008760 SourceLocation UsingLoc,
8761 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008762 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008763 SourceLocation IdentLoc,
8764 IdentifierInfo *NamespcName,
8765 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008766 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8767 assert(NamespcName && "Invalid NamespcName.");
8768 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008769
8770 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008771 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008772 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008773 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008774
Craig Topperc3ec1492014-05-26 06:22:03 +00008775 UsingDirectiveDecl *UDir = nullptr;
8776 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008777 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008778 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008779
Douglas Gregor34074322009-01-14 22:20:51 +00008780 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008781 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8782 LookupParsedName(R, S, &SS);
8783 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008784 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008785
Douglas Gregorcdf87022010-06-29 17:53:46 +00008786 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008787 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008788 // Allow "using namespace std;" or "using namespace ::std;" even if
8789 // "std" hasn't been defined yet, for GCC compatibility.
8790 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8791 NamespcName->isStr("std")) {
8792 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008793 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008794 R.resolveKind();
8795 }
8796 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008797 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008798 }
8799
John McCall9f3059a2009-10-09 21:13:30 +00008800 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008801 NamedDecl *Named = R.getRepresentativeDecl();
8802 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8803 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008804
Nico Riecke50e59a2014-11-24 17:29:52 +00008805 // The use of a nested name specifier may trigger deprecation warnings.
8806 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008807
Douglas Gregor889ceb72009-02-03 19:21:40 +00008808 // C++ [namespace.udir]p1:
8809 // A using-directive specifies that the names in the nominated
8810 // namespace can be used in the scope in which the
8811 // using-directive appears after the using-directive. During
8812 // unqualified name lookup (3.4.1), the names appear as if they
8813 // were declared in the nearest enclosing namespace which
8814 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008815 // namespace. [Note: in this context, "contains" means "contains
8816 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008817
8818 // Find enclosing context containing both using-directive and
8819 // nominated namespace.
8820 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8821 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8822 CommonAncestor = CommonAncestor->getParent();
8823
Sebastian Redla6602e92009-11-23 15:34:23 +00008824 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008825 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008826 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008827
Douglas Gregora172e082011-03-26 22:25:30 +00008828 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008829 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008830 Diag(IdentLoc, diag::warn_using_directive_in_header);
8831 }
8832
Douglas Gregor889ceb72009-02-03 19:21:40 +00008833 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008834 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008835 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008836 }
8837
Richard Smith54ecd982013-02-20 19:22:51 +00008838 if (UDir)
8839 ProcessDeclAttributeList(S, UDir, AttrList);
8840
John McCall48871652010-08-21 09:40:31 +00008841 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008842}
8843
8844void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008845 // If the scope has an associated entity and the using directive is at
8846 // namespace or translation unit scope, add the UsingDirectiveDecl into
8847 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008848 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008849 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008850 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008851 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008852 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008853 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008854 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008855}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008856
Douglas Gregorfec52632009-06-20 00:51:54 +00008857
John McCall48871652010-08-21 09:40:31 +00008858Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008859 AccessSpecifier AS,
John McCall9b72f892010-11-10 02:40:36 +00008860 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008861 SourceLocation TypenameLoc,
John McCall9b72f892010-11-10 02:40:36 +00008862 CXXScopeSpec &SS,
8863 UnqualifiedId &Name,
Richard Smith151c4562016-12-20 21:35:28 +00008864 SourceLocation EllipsisLoc,
8865 AttributeList *AttrList) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008866 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008867
Richard Smith151c4562016-12-20 21:35:28 +00008868 if (SS.isEmpty()) {
8869 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8870 return nullptr;
8871 }
8872
Douglas Gregor220f4272009-11-04 16:30:06 +00008873 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008874 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008875 case UnqualifiedId::IK_Identifier:
8876 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008877 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008878 case UnqualifiedId::IK_ConversionFunctionId:
8879 break;
8880
8881 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008882 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008883 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008884 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008885 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008886 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008887 diag::err_using_decl_constructor)
8888 << SS.getRange();
8889
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008890 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008891
Craig Topperc3ec1492014-05-26 06:22:03 +00008892 return nullptr;
8893
Douglas Gregor220f4272009-11-04 16:30:06 +00008894 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008895 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008896 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008897 return nullptr;
8898
Douglas Gregor220f4272009-11-04 16:30:06 +00008899 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008900 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008901 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008902 return nullptr;
Richard Smith35845152017-02-07 01:37:30 +00008903
8904 case UnqualifiedId::IK_DeductionGuideName:
8905 llvm_unreachable("cannot parse qualified deduction guide name");
Douglas Gregor220f4272009-11-04 16:30:06 +00008906 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008907
8908 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8909 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008910 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008911 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008912
Richard Smithc2bc61b2013-03-18 21:12:30 +00008913 // Warn about access declarations.
Richard Smith6f1daa42016-12-16 00:58:48 +00008914 if (UsingLoc.isInvalid()) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008915 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008916 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8917 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008918 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008919 }
8920
Richard Smith151c4562016-12-20 21:35:28 +00008921 if (EllipsisLoc.isInvalid()) {
8922 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8923 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8924 return nullptr;
8925 } else {
8926 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8927 !TargetNameInfo.containsUnexpandedParameterPack()) {
8928 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8929 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8930 EllipsisLoc = SourceLocation();
8931 }
8932 }
Douglas Gregorc4356532010-12-16 00:46:58 +00008933
Richard Smith151c4562016-12-20 21:35:28 +00008934 NamedDecl *UD =
8935 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8936 SS, TargetNameInfo, EllipsisLoc, AttrList,
8937 /*IsInstantiation*/false);
John McCallb96ec562009-12-04 22:46:56 +00008938 if (UD)
8939 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008940
John McCall48871652010-08-21 09:40:31 +00008941 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008942}
8943
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008944/// \brief Determine whether a using declaration considers the given
8945/// declarations as "equivalent", e.g., if they are redeclarations of
8946/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008947static bool
8948IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8949 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008950 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008951
Richard Smithdda56e42011-04-15 14:24:37 +00008952 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008953 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008954 return Context.hasSameType(TD1->getUnderlyingType(),
8955 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008956
8957 return false;
8958}
8959
8960
John McCall84d87672009-12-10 09:41:52 +00008961/// Determines whether to create a using shadow decl for a particular
8962/// decl, given the set of decls existing prior to this using lookup.
8963bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008964 const LookupResult &Previous,
8965 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008966 // Diagnose finding a decl which is not from a base class of the
8967 // current class. We do this now because there are cases where this
8968 // function will silently decide not to build a shadow decl, which
8969 // will pre-empt further diagnostics.
8970 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008971 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008972 // the qualifier.
8973 //
8974 // FIXME: diagnose the following if we care enough:
8975 // struct A { int foo; };
8976 // struct B : A { using A::foo; };
8977 // template <class T> struct C : A {};
8978 // template <class T> struct D : C<T> { using B::foo; } // <---
8979 // This is invalid (during instantiation) in C++03 because B::foo
8980 // resolves to the using decl in B, which is not a base class of D<T>.
8981 // We can't diagnose it immediately because C<T> is an unknown
8982 // specialization. The UsingShadowDecl in D<T> then points directly
8983 // to A::foo, which will look well-formed when we instantiate.
8984 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008985 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008986 DeclContext *OrigDC = Orig->getDeclContext();
8987
8988 // Handle enums and anonymous structs.
8989 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8990 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8991 while (OrigRec->isAnonymousStructOrUnion())
8992 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8993
8994 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8995 if (OrigDC == CurContext) {
8996 Diag(Using->getLocation(),
8997 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008998 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008999 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00009000 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009001 return true;
9002 }
9003
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009004 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00009005 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009006 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00009007 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009008 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00009009 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00009010 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009011 return true;
9012 }
9013 }
9014
9015 if (Previous.empty()) return false;
9016
9017 NamedDecl *Target = Orig;
9018 if (isa<UsingShadowDecl>(Target))
9019 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9020
John McCalla17e83e2009-12-11 02:33:26 +00009021 // If the target happens to be one of the previous declarations, we
9022 // don't have a conflict.
9023 //
9024 // FIXME: but we might be increasing its access, in which case we
9025 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00009026 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009027 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00009028 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9029 I != E; ++I) {
9030 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00009031 // We can have UsingDecls in our Previous results because we use the same
9032 // LookupResult for checking whether the UsingDecl itself is a valid
9033 // redeclaration.
Richard Smith151c4562016-12-20 21:35:28 +00009034 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
Richard Smithe5a91462016-02-27 02:36:43 +00009035 continue;
9036
Richard Smithfd8634a2013-10-23 02:17:46 +00009037 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9038 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9039 PrevShadow = Shadow;
9040 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00009041 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9042 // We don't conflict with an existing using shadow decl of an equivalent
9043 // declaration, but we're not a redeclaration of it.
9044 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00009045 }
John McCalla17e83e2009-12-11 02:33:26 +00009046
Richard Smithf091e122015-09-15 01:28:55 +00009047 if (isVisible(D))
9048 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00009049 }
9050
Richard Smithfd8634a2013-10-23 02:17:46 +00009051 if (FoundEquivalentDecl)
9052 return false;
9053
Alp Tokera2794f92014-01-22 07:29:52 +00009054 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009055 NamedDecl *OldDecl = nullptr;
9056 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9057 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00009058 case Ovl_Overload:
9059 return false;
9060
9061 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00009062 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009063 break;
Richard Smith18819302014-02-06 01:31:33 +00009064
John McCall84d87672009-12-10 09:41:52 +00009065 // We found a decl with the exact signature.
9066 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00009067 // If we're in a record, we want to hide the target, so we
9068 // return true (without a diagnostic) to tell the caller not to
9069 // build a shadow decl.
9070 if (CurContext->isRecord())
9071 return true;
9072
9073 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00009074 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009075 break;
9076 }
9077
9078 Diag(Target->getLocation(), diag::note_using_decl_target);
9079 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009080 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009081 return true;
9082 }
9083
9084 // Target is not a function.
9085
John McCall84d87672009-12-10 09:41:52 +00009086 if (isa<TagDecl>(Target)) {
9087 // No conflict between a tag and a non-tag.
9088 if (!Tag) return false;
9089
John McCalle29c5cd2009-12-10 19:51:03 +00009090 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009091 Diag(Target->getLocation(), diag::note_using_decl_target);
9092 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009093 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009094 return true;
9095 }
9096
9097 // No conflict between a tag and a non-tag.
9098 if (!NonTag) return false;
9099
John McCalle29c5cd2009-12-10 19:51:03 +00009100 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009101 Diag(Target->getLocation(), diag::note_using_decl_target);
9102 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009103 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009104 return true;
9105}
9106
Richard Smith5179eb72016-06-28 19:03:57 +00009107/// Determine whether a direct base class is a virtual base class.
9108static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9109 if (!Derived->getNumVBases())
9110 return false;
9111 for (auto &B : Derived->bases())
9112 if (B.getType()->getAsCXXRecordDecl() == Base)
9113 return B.isVirtual();
9114 llvm_unreachable("not a direct base class");
9115}
9116
John McCall3f746822009-11-17 05:59:44 +00009117/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00009118UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00009119 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00009120 NamedDecl *Orig,
9121 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00009122 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00009123 NamedDecl *Target = Orig;
9124 if (isa<UsingShadowDecl>(Target)) {
9125 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9126 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00009127 }
Richard Smithfd8634a2013-10-23 02:17:46 +00009128
Richard Smith5179eb72016-06-28 19:03:57 +00009129 NamedDecl *NonTemplateTarget = Target;
9130 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9131 NonTemplateTarget = TargetTD->getTemplatedDecl();
9132
9133 UsingShadowDecl *Shadow;
9134 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9135 bool IsVirtualBase =
9136 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9137 UD->getQualifier()->getAsRecordDecl());
9138 Shadow = ConstructorUsingShadowDecl::Create(
9139 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9140 } else {
9141 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9142 Target);
9143 }
John McCall3f746822009-11-17 05:59:44 +00009144 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00009145
Douglas Gregor457104e2010-09-29 04:25:11 +00009146 Shadow->setAccess(UD->getAccess());
9147 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9148 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00009149
9150 Shadow->setPreviousDecl(PrevDecl);
9151
John McCall3f746822009-11-17 05:59:44 +00009152 if (S)
John McCall3969e302009-12-08 07:46:18 +00009153 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00009154 else
John McCall3969e302009-12-08 07:46:18 +00009155 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00009156
John McCall3969e302009-12-08 07:46:18 +00009157
John McCall84d87672009-12-10 09:41:52 +00009158 return Shadow;
9159}
John McCall3969e302009-12-08 07:46:18 +00009160
John McCall84d87672009-12-10 09:41:52 +00009161/// Hides a using shadow declaration. This is required by the current
9162/// using-decl implementation when a resolvable using declaration in a
9163/// class is followed by a declaration which would hide or override
9164/// one or more of the using decl's targets; for example:
9165///
9166/// struct Base { void foo(int); };
9167/// struct Derived : Base {
9168/// using Base::foo;
9169/// void foo(int);
9170/// };
9171///
9172/// The governing language is C++03 [namespace.udecl]p12:
9173///
9174/// When a using-declaration brings names from a base class into a
9175/// derived class scope, member functions in the derived class
9176/// override and/or hide member functions with the same name and
9177/// parameter types in a base class (rather than conflicting).
9178///
9179/// There are two ways to implement this:
9180/// (1) optimistically create shadow decls when they're not hidden
9181/// by existing declarations, or
9182/// (2) don't create any shadow decls (or at least don't make them
9183/// visible) until we've fully parsed/instantiated the class.
9184/// The problem with (1) is that we might have to retroactively remove
9185/// a shadow decl, which requires several O(n) operations because the
9186/// decl structures are (very reasonably) not designed for removal.
9187/// (2) avoids this but is very fiddly and phase-dependent.
9188void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00009189 if (Shadow->getDeclName().getNameKind() ==
9190 DeclarationName::CXXConversionFunctionName)
9191 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9192
John McCall84d87672009-12-10 09:41:52 +00009193 // Remove it from the DeclContext...
9194 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009195
John McCall84d87672009-12-10 09:41:52 +00009196 // ...and the scope, if applicable...
9197 if (S) {
John McCall48871652010-08-21 09:40:31 +00009198 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00009199 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009200 }
9201
John McCall84d87672009-12-10 09:41:52 +00009202 // ...and the using decl.
9203 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9204
9205 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00009206 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00009207}
9208
Richard Smith09d5b3a2014-05-01 00:35:04 +00009209/// Find the base specifier for a base class with the given type.
9210static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9211 QualType DesiredBase,
9212 bool &AnyDependentBases) {
9213 // Check whether the named type is a direct base class.
9214 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9215 for (auto &Base : Derived->bases()) {
9216 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9217 if (CanonicalDesiredBase == BaseType)
9218 return &Base;
9219 if (BaseType->isDependentType())
9220 AnyDependentBases = true;
9221 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009222 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009223}
9224
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009225namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009226class UsingValidatorCCC : public CorrectionCandidateCallback {
9227public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00009228 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009229 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009230 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00009231 IsInstantiation(IsInstantiation), OldNNS(NNS),
9232 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009233
Craig Toppera798a9d2014-03-02 09:32:10 +00009234 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009235 NamedDecl *ND = Candidate.getCorrectionDecl();
9236
9237 // Keywords are not valid here.
9238 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009239 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009240
9241 // Completely unqualified names are invalid for a 'using' declaration.
9242 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9243 return false;
9244
Richard Smith9385d702016-05-14 01:58:49 +00009245 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9246 // reject.
9247
Richard Smith09d5b3a2014-05-01 00:35:04 +00009248 if (RequireMemberOf) {
9249 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9250 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9251 // No-one ever wants a using-declaration to name an injected-class-name
9252 // of a base class, unless they're declaring an inheriting constructor.
9253 ASTContext &Ctx = ND->getASTContext();
9254 if (!Ctx.getLangOpts().CPlusPlus11)
9255 return false;
9256 QualType FoundType = Ctx.getRecordType(FoundRecord);
9257
9258 // Check that the injected-class-name is named as a member of its own
9259 // type; we don't want to suggest 'using Derived::Base;', since that
9260 // means something else.
9261 NestedNameSpecifier *Specifier =
9262 Candidate.WillReplaceSpecifier()
9263 ? Candidate.getCorrectionSpecifier()
9264 : OldNNS;
9265 if (!Specifier->getAsType() ||
9266 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9267 return false;
9268
9269 // Check that this inheriting constructor declaration actually names a
9270 // direct base class of the current class.
9271 bool AnyDependentBases = false;
9272 if (!findDirectBaseWithType(RequireMemberOf,
9273 Ctx.getRecordType(FoundRecord),
9274 AnyDependentBases) &&
9275 !AnyDependentBases)
9276 return false;
9277 } else {
9278 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9279 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9280 return false;
9281
9282 // FIXME: Check that the base class member is accessible?
9283 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00009284 } else {
9285 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9286 if (FoundRecord && FoundRecord->isInjectedClassName())
9287 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009288 }
9289
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009290 if (isa<TypeDecl>(ND))
9291 return HasTypenameKeyword || !IsInstantiation;
9292
9293 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009294 }
9295
9296private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009297 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009298 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009299 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009300 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009301};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009302} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009303
John McCalle61f2ba2009-11-18 02:36:19 +00009304/// Builds a using declaration.
9305///
9306/// \param IsInstantiation - Whether this call arises from an
9307/// instantiation of an unresolved using declaration. We treat
9308/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009309NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9310 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009311 bool HasTypenameKeyword,
9312 SourceLocation TypenameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009313 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009314 DeclarationNameInfo NameInfo,
Richard Smith151c4562016-12-20 21:35:28 +00009315 SourceLocation EllipsisLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009316 AttributeList *AttrList,
Richard Smith151c4562016-12-20 21:35:28 +00009317 bool IsInstantiation) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009318 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009319 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009320 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009321
Anders Carlssonf038fc22009-08-28 05:49:21 +00009322 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009323
Richard Smith5179eb72016-06-28 19:03:57 +00009324 // For an inheriting constructor declaration, the name of the using
9325 // declaration is the name of a constructor in this class, not in the
9326 // base class.
9327 DeclarationNameInfo UsingName = NameInfo;
9328 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9329 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9330 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9331 Context.getCanonicalType(Context.getRecordType(RD))));
9332
John McCall84d87672009-12-10 09:41:52 +00009333 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009334 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009335 ForRedeclaration);
9336 Previous.setHideTags(false);
9337 if (S) {
9338 LookupName(Previous, S);
9339
9340 // It is really dumb that we have to do this.
9341 LookupResult::Filter F = Previous.makeFilter();
9342 while (F.hasNext()) {
9343 NamedDecl *D = F.next();
9344 if (!isDeclInScope(D, CurContext, S))
9345 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009346 // If we found a local extern declaration that's not ordinarily visible,
9347 // and this declaration is being added to a non-block scope, ignore it.
9348 // We're only checking for scope conflicts here, not also for violations
9349 // of the linkage rules.
9350 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9351 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9352 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009353 }
9354 F.done();
9355 } else {
9356 assert(IsInstantiation && "no scope in non-instantiation");
Richard Smithd8a9e372016-12-18 21:39:37 +00009357 if (CurContext->isRecord())
9358 LookupQualifiedName(Previous, CurContext);
9359 else {
9360 // No redeclaration check is needed here; in non-member contexts we
9361 // diagnosed all possible conflicts with other using-declarations when
9362 // building the template:
9363 //
9364 // For a dependent non-type using declaration, the only valid case is
9365 // if we instantiate to a single enumerator. We check for conflicts
9366 // between shadow declarations we introduce, and we check in the template
9367 // definition for conflicts between a non-type using declaration and any
9368 // other declaration, which together covers all cases.
9369 //
9370 // A dependent typename using declaration will never successfully
9371 // instantiate, since it will always name a class member, so we reject
9372 // that in the template definition.
9373 }
John McCall84d87672009-12-10 09:41:52 +00009374 }
9375
John McCall84d87672009-12-10 09:41:52 +00009376 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009377 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9378 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009379 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009380
9381 // Check for bad qualifiers.
Richard Smithd8a9e372016-12-18 21:39:37 +00009382 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9383 IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009384 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009385
John McCall84c16cf2009-11-12 03:15:40 +00009386 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009387 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009388 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Richard Smith151c4562016-12-20 21:35:28 +00009389 if (!LookupContext || EllipsisLoc.isValid()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009390 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009391 // FIXME: not all declaration name kinds are legal here
9392 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9393 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009394 QualifierLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009395 IdentLoc, NameInfo.getName(),
9396 EllipsisLoc);
John McCallb96ec562009-12-04 22:46:56 +00009397 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009398 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009399 QualifierLoc, NameInfo, EllipsisLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00009400 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009401 D->setAccess(AS);
9402 CurContext->addDecl(D);
9403 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009404 }
John McCallb96ec562009-12-04 22:46:56 +00009405
Richard Smith09d5b3a2014-05-01 00:35:04 +00009406 auto Build = [&](bool Invalid) {
9407 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009408 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9409 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009410 UD->setAccess(AS);
9411 CurContext->addDecl(UD);
9412 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009413 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009414 };
9415 auto BuildInvalid = [&]{ return Build(true); };
9416 auto BuildValid = [&]{ return Build(false); };
9417
9418 if (RequireCompleteDeclContext(SS, LookupContext))
9419 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009420
Richard Smith78163e22015-04-01 19:31:06 +00009421 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009422 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009423
John McCall3969e302009-12-08 07:46:18 +00009424 // Unlike most lookups, we don't always want to hide tag
9425 // declarations: tag names are visible through the using declaration
9426 // even if hidden by ordinary names, *except* in a dependent context
9427 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009428 if (!IsInstantiation)
9429 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009430
John McCall5dadb652012-04-07 03:04:20 +00009431 // For the purposes of this lookup, we have a base object type
9432 // equal to that of the current context.
9433 if (CurContext->isRecord()) {
9434 R.setBaseObjectType(
9435 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9436 }
9437
John McCall27b18f82009-11-17 02:14:36 +00009438 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009439
Richard Smith78163e22015-04-01 19:31:06 +00009440 // Try to correct typos if possible. If constructor name lookup finds no
9441 // results, that means the named class has no explicit constructors, and we
9442 // suppressed declaring implicit ones (probably because it's dependent or
9443 // invalid).
9444 if (R.empty() &&
9445 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Richard Smith46d04a32017-01-08 04:01:15 +00009446 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9447 // it will believe that glibc provides a ::gets in cases where it does not,
9448 // and will try to pull it into namespace std with a using-declaration.
9449 // Just ignore the using-declaration in that case.
9450 auto *II = NameInfo.getName().getAsIdentifierInfo();
9451 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9452 CurContext->isStdNamespace() &&
9453 isa<TranslationUnitDecl>(LookupContext) &&
9454 getSourceManager().isInSystemHeader(UsingLoc))
9455 return nullptr;
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009456 if (TypoCorrection Corrected = CorrectTypo(
9457 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9458 llvm::make_unique<UsingValidatorCCC>(
9459 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9460 dyn_cast<CXXRecordDecl>(CurContext)),
9461 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00009462 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009463 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009464 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9465 << NameInfo.getName() << LookupContext << 0
9466 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009467
Benjamin Kramerae65d222017-01-24 12:49:59 +00009468 // If we picked a correction with no attached Decl we can't do anything
9469 // useful with it, bail out.
9470 NamedDecl *ND = Corrected.getCorrectionDecl();
9471 if (!ND)
9472 return BuildInvalid();
9473
Richard Smith09d5b3a2014-05-01 00:35:04 +00009474 // If we corrected to an inheriting constructor, handle it as one.
9475 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9476 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009477 // The parent of the injected class name is the class itself.
9478 RD = cast<CXXRecordDecl>(RD->getParent());
9479
Richard Smith09d5b3a2014-05-01 00:35:04 +00009480 // Fix up the information we'll use to build the using declaration.
9481 if (Corrected.WillReplaceSpecifier()) {
9482 NestedNameSpecifierLocBuilder Builder;
9483 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9484 QualifierLoc.getSourceRange());
9485 QualifierLoc = Builder.getWithLocInContext(Context);
9486 }
9487
Richard Smith5179eb72016-06-28 19:03:57 +00009488 // In this case, the name we introduce is the name of a derived class
9489 // constructor.
9490 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9491 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9492 Context.getCanonicalType(Context.getRecordType(CurClass))));
9493 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009494 for (auto *Ctor : LookupConstructors(RD))
9495 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009496 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009497 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009498 // FIXME: Pick up all the declarations if we found an overloaded
9499 // function.
9500 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009501 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009502 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009503 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009504 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009505 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009506 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009507 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009508 }
9509
Richard Smith09d5b3a2014-05-01 00:35:04 +00009510 if (R.isAmbiguous())
9511 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009512
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009513 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009514 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009515 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009516 Diag(IdentLoc, diag::err_using_typename_non_type);
9517 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9518 Diag((*I)->getUnderlyingDecl()->getLocation(),
9519 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009520 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009521 }
9522 } else {
9523 // If we asked for a non-typename and we got a type, error out,
9524 // but only if this is an instantiation of an unresolved using
9525 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009526 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009527 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9528 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009529 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009530 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009531 }
9532
Richard Smith5cbeb752016-05-05 02:13:49 +00009533 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009534 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009535 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009536 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9537 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009538 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009539 }
Mike Stump11289f42009-09-09 15:08:12 +00009540
Richard Smith5cbeb752016-05-05 02:13:49 +00009541 // C++14 [namespace.udecl]p7:
9542 // A using-declaration shall not name a scoped enumerator.
9543 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9544 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9545 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9546 << SS.getRange();
9547 return BuildInvalid();
9548 }
9549 }
9550
Richard Smith09d5b3a2014-05-01 00:35:04 +00009551 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009552
Richard Smith5179eb72016-06-28 19:03:57 +00009553 // Some additional rules apply to inheriting constructors.
9554 if (UsingName.getName().getNameKind() ==
9555 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009556 // Suppress access diagnostics; the access check is instead performed at the
9557 // point of use for an inheriting constructor.
9558 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009559 if (CheckInheritingConstructorUsingDecl(UD))
9560 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009561 }
9562
John McCall84d87672009-12-10 09:41:52 +00009563 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009564 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009565 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9566 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009567 }
John McCall3f746822009-11-17 05:59:44 +00009568
9569 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009570}
9571
Richard Smith151c4562016-12-20 21:35:28 +00009572NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9573 ArrayRef<NamedDecl *> Expansions) {
9574 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9575 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9576 isa<UsingPackDecl>(InstantiatedFrom));
9577
9578 auto *UPD =
9579 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9580 UPD->setAccess(InstantiatedFrom->getAccess());
9581 CurContext->addDecl(UPD);
9582 return UPD;
9583}
9584
Sebastian Redl08905022011-02-05 19:23:19 +00009585/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009586bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009587 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009588
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009589 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009590 assert(SourceType &&
9591 "Using decl naming constructor doesn't have type in scope spec.");
9592 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9593
9594 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009595 bool AnyDependentBases = false;
9596 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9597 AnyDependentBases);
9598 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009599 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009600 diag::err_using_decl_constructor_not_in_direct_base)
9601 << UD->getNameInfo().getSourceRange()
9602 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009603 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009604 return true;
9605 }
9606
Richard Smith09d5b3a2014-05-01 00:35:04 +00009607 if (Base)
9608 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009609
9610 return false;
9611}
9612
John McCall84d87672009-12-10 09:41:52 +00009613/// Checks that the given using declaration is not an invalid
9614/// redeclaration. Note that this is checking only for the using decl
9615/// itself, not for any ill-formedness among the UsingShadowDecls.
9616bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009617 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009618 const CXXScopeSpec &SS,
9619 SourceLocation NameLoc,
9620 const LookupResult &Prev) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009621 NestedNameSpecifier *Qual = SS.getScopeRep();
9622
John McCall84d87672009-12-10 09:41:52 +00009623 // C++03 [namespace.udecl]p8:
9624 // C++0x [namespace.udecl]p10:
9625 // A using-declaration is a declaration and can therefore be used
9626 // repeatedly where (and only where) multiple declarations are
9627 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009628 //
John McCall032092f2010-11-29 18:01:58 +00009629 // That's in non-member contexts.
Richard Smith4eeaec42016-12-18 22:01:46 +00009630 if (!CurContext->getRedeclContext()->isRecord()) {
9631 // A dependent qualifier outside a class can only ever resolve to an
9632 // enumeration type. Therefore it conflicts with any other non-type
9633 // declaration in the same scope.
9634 // FIXME: How should we check for dependent type-type conflicts at block
9635 // scope?
9636 if (Qual->isDependent() && !HasTypenameKeyword) {
9637 for (auto *D : Prev) {
Richard Smith151c4562016-12-20 21:35:28 +00009638 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009639 bool OldCouldBeEnumerator =
9640 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9641 Diag(NameLoc,
9642 OldCouldBeEnumerator ? diag::err_redefinition
9643 : diag::err_redefinition_different_kind)
9644 << Prev.getLookupName();
9645 Diag(D->getLocation(), diag::note_previous_definition);
9646 return true;
9647 }
9648 }
9649 }
John McCall84d87672009-12-10 09:41:52 +00009650 return false;
Richard Smith4eeaec42016-12-18 22:01:46 +00009651 }
John McCall84d87672009-12-10 09:41:52 +00009652
9653 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9654 NamedDecl *D = *I;
9655
9656 bool DTypename;
9657 NestedNameSpecifier *DQual;
9658 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009659 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009660 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009661 } else if (UnresolvedUsingValueDecl *UD
9662 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9663 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009664 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009665 } else if (UnresolvedUsingTypenameDecl *UD
9666 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9667 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009668 DQual = UD->getQualifier();
Richard Smith4eeaec42016-12-18 22:01:46 +00009669 } else continue;
John McCall84d87672009-12-10 09:41:52 +00009670
9671 // using decls differ if one says 'typename' and the other doesn't.
9672 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009673 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009674
9675 // using decls differ if they name different scopes (but note that
9676 // template instantiation can cause this check to trigger when it
9677 // didn't before instantiation).
9678 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9679 Context.getCanonicalNestedNameSpecifier(DQual))
9680 continue;
9681
9682 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009683 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009684 return true;
9685 }
9686
9687 return false;
9688}
9689
John McCall3969e302009-12-08 07:46:18 +00009690
John McCallb96ec562009-12-04 22:46:56 +00009691/// Checks that the given nested-name qualifier used in a using decl
9692/// in the current context is appropriately related to the current
9693/// scope. If an error is found, diagnoses it and returns true.
9694bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
Richard Smithd8a9e372016-12-18 21:39:37 +00009695 bool HasTypename,
John McCallb96ec562009-12-04 22:46:56 +00009696 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009697 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009698 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009699 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009700
John McCall3969e302009-12-08 07:46:18 +00009701 if (!CurContext->isRecord()) {
9702 // C++03 [namespace.udecl]p3:
9703 // C++0x [namespace.udecl]p8:
9704 // A using-declaration for a class member shall be a member-declaration.
9705
Richard Smithd8a9e372016-12-18 21:39:37 +00009706 // If we weren't able to compute a valid scope, it might validly be a
9707 // dependent class scope or a dependent enumeration unscoped scope. If
9708 // we have a 'typename' keyword, the scope must resolve to a class type.
9709 if ((HasTypename && !NamedContext) ||
9710 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009711 auto *RD = NamedContext
9712 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9713 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009714 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009715 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009716
John McCall3969e302009-12-08 07:46:18 +00009717 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9718 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009719
9720 // If we have a complete, non-dependent source type, try to suggest a
9721 // way to get the same effect.
9722 if (!RD)
9723 return true;
9724
9725 // Find what this using-declaration was referring to.
9726 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9727 R.setHideTags(false);
9728 R.suppressDiagnostics();
9729 LookupQualifiedName(R, RD);
9730
9731 if (R.getAsSingle<TypeDecl>()) {
9732 if (getLangOpts().CPlusPlus11) {
9733 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9734 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9735 << 0 // alias declaration
9736 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9737 NameInfo.getName().getAsString() +
9738 " = ");
9739 } else {
9740 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9741 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009742 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009743 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9744 << 1 // typedef declaration
9745 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9746 << FixItHint::CreateInsertion(
9747 InsertLoc, " " + NameInfo.getName().getAsString());
9748 }
9749 } else if (R.getAsSingle<VarDecl>()) {
9750 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9751 // repeating the type of the static data member here.
9752 FixItHint FixIt;
9753 if (getLangOpts().CPlusPlus11) {
9754 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9755 FixIt = FixItHint::CreateReplacement(
9756 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9757 }
9758
9759 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9760 << 2 // reference declaration
9761 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009762 } else if (R.getAsSingle<EnumConstantDecl>()) {
9763 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9764 // repeating the type of the enumeration here, and we can't do so if
9765 // the type is anonymous.
9766 FixItHint FixIt;
9767 if (getLangOpts().CPlusPlus11) {
9768 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9769 FixIt = FixItHint::CreateReplacement(
Richard Smithd8a9e372016-12-18 21:39:37 +00009770 UsingLoc,
9771 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
Richard Smithdce10ea2016-05-05 19:16:15 +00009772 }
9773
9774 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9775 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9776 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009777 }
John McCall3969e302009-12-08 07:46:18 +00009778 return true;
9779 }
9780
Richard Smithd8a9e372016-12-18 21:39:37 +00009781 // Otherwise, this might be valid.
John McCall3969e302009-12-08 07:46:18 +00009782 return false;
9783 }
9784
9785 // The current scope is a record.
9786
9787 // If the named context is dependent, we can't decide much.
9788 if (!NamedContext) {
9789 // FIXME: in C++0x, we can diagnose if we can prove that the
9790 // nested-name-specifier does not refer to a base class, which is
9791 // still possible in some cases.
9792
9793 // Otherwise we have to conservatively report that things might be
9794 // okay.
9795 return false;
9796 }
9797
9798 if (!NamedContext->isRecord()) {
9799 // Ideally this would point at the last name in the specifier,
9800 // but we don't have that level of source info.
9801 Diag(SS.getRange().getBegin(),
9802 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009803 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009804 return true;
9805 }
9806
Douglas Gregor7c842292010-12-21 07:41:49 +00009807 if (!NamedContext->isDependentContext() &&
9808 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9809 return true;
9810
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009811 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009812 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009813 // In a using-declaration used as a member-declaration, the
9814 // nested-name-specifier shall name a base class of the class
9815 // being defined.
9816
9817 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9818 cast<CXXRecordDecl>(NamedContext))) {
9819 if (CurContext == NamedContext) {
9820 Diag(NameLoc,
9821 diag::err_using_decl_nested_name_specifier_is_current_class)
9822 << SS.getRange();
9823 return true;
9824 }
9825
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009826 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9827 Diag(SS.getRange().getBegin(),
9828 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9829 << SS.getScopeRep()
9830 << cast<CXXRecordDecl>(CurContext)
9831 << SS.getRange();
9832 }
John McCall3969e302009-12-08 07:46:18 +00009833 return true;
9834 }
9835
9836 return false;
9837 }
9838
9839 // C++03 [namespace.udecl]p4:
9840 // A using-declaration used as a member-declaration shall refer
9841 // to a member of a base class of the class being defined [etc.].
9842
9843 // Salient point: SS doesn't have to name a base class as long as
9844 // lookup only finds members from base classes. Therefore we can
9845 // diagnose here only if we can prove that that can't happen,
9846 // i.e. if the class hierarchies provably don't intersect.
9847
9848 // TODO: it would be nice if "definitely valid" results were cached
9849 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9850 // need to be repeated.
9851
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009852 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9853 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9854 Bases.insert(Base);
9855 return true;
John McCall3969e302009-12-08 07:46:18 +00009856 };
9857
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009858 // Collect all bases. Return false if we find a dependent base.
9859 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009860 return false;
9861
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009862 // Returns true if the base is dependent or is one of the accumulated base
9863 // classes.
9864 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9865 return !Bases.count(Base);
9866 };
9867
9868 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009869 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009870 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9871 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009872 return false;
9873
9874 Diag(SS.getRange().getBegin(),
9875 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009876 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009877 << cast<CXXRecordDecl>(CurContext)
9878 << SS.getRange();
9879
9880 return true;
John McCallb96ec562009-12-04 22:46:56 +00009881}
9882
Richard Smithdda56e42011-04-15 14:24:37 +00009883Decl *Sema::ActOnAliasDeclaration(Scope *S,
9884 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009885 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009886 SourceLocation UsingLoc,
9887 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009888 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009889 TypeResult Type,
9890 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009891 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009892 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009893 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009894 assert((S->getFlags() & Scope::DeclScope) &&
9895 "got alias-declaration outside of declaration scope");
9896
9897 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009898 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009899
9900 bool Invalid = false;
9901 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009902 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009903 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009904
9905 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009906 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009907
9908 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009909 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009910 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009911 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9912 TInfo->getTypeLoc().getBeginLoc());
9913 }
Richard Smithdda56e42011-04-15 14:24:37 +00009914
9915 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9916 LookupName(Previous, S);
9917
9918 // Warn about shadowing the name of a template parameter.
9919 if (Previous.isSingleResult() &&
9920 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009921 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009922 Previous.clear();
9923 }
9924
9925 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9926 "name in alias declaration must be an identifier");
9927 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9928 Name.StartLocation,
9929 Name.Identifier, TInfo);
9930
9931 NewTD->setAccess(AS);
9932
9933 if (Invalid)
9934 NewTD->setInvalidDecl();
9935
Richard Smith54ecd982013-02-20 19:22:51 +00009936 ProcessDeclAttributeList(S, NewTD, AttrList);
9937
Richard Smith3f1b5d02011-05-05 21:57:07 +00009938 CheckTypedefForVariablyModifiedType(S, NewTD);
9939 Invalid |= NewTD->isInvalidDecl();
9940
Richard Smithdda56e42011-04-15 14:24:37 +00009941 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009942
9943 NamedDecl *NewND;
9944 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009945 TypeAliasTemplateDecl *OldDecl = nullptr;
9946 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009947
9948 if (TemplateParamLists.size() != 1) {
9949 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009950 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9951 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009952 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009953 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009954
Richard Smith882593f2016-04-06 17:38:58 +00009955 // Check that we can declare a template here.
9956 if (CheckTemplateDeclScope(S, TemplateParams))
9957 return nullptr;
9958
Richard Smith3f1b5d02011-05-05 21:57:07 +00009959 // Only consider previous declarations in the same scope.
9960 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9961 /*ExplicitInstantiationOrSpecialization*/false);
9962 if (!Previous.empty()) {
9963 Redeclaration = true;
9964
9965 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9966 if (!OldDecl && !Invalid) {
9967 Diag(UsingLoc, diag::err_redefinition_different_kind)
9968 << Name.Identifier;
9969
9970 NamedDecl *OldD = Previous.getRepresentativeDecl();
9971 if (OldD->getLocation().isValid())
9972 Diag(OldD->getLocation(), diag::note_previous_definition);
9973
9974 Invalid = true;
9975 }
9976
9977 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9978 if (TemplateParameterListsAreEqual(TemplateParams,
9979 OldDecl->getTemplateParameters(),
9980 /*Complain=*/true,
9981 TPL_TemplateMatch))
9982 OldTemplateParams = OldDecl->getTemplateParameters();
9983 else
9984 Invalid = true;
9985
9986 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9987 if (!Invalid &&
9988 !Context.hasSameType(OldTD->getUnderlyingType(),
9989 NewTD->getUnderlyingType())) {
9990 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9991 // but we can't reasonably accept it.
9992 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9993 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9994 if (OldTD->getLocation().isValid())
9995 Diag(OldTD->getLocation(), diag::note_previous_definition);
9996 Invalid = true;
9997 }
9998 }
9999 }
10000
10001 // Merge any previous default template arguments into our parameters,
10002 // and check the parameter list.
10003 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10004 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +000010005 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +000010006
10007 TypeAliasTemplateDecl *NewDecl =
10008 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10009 Name.Identifier, TemplateParams,
10010 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +000010011 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010012
10013 NewDecl->setAccess(AS);
10014
10015 if (Invalid)
10016 NewDecl->setInvalidDecl();
10017 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +000010018 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010019
10020 NewND = NewDecl;
10021 } else {
David Majnemerf9bde282015-03-11 06:45:39 +000010022 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10023 setTagNameForLinkagePurposes(TD, NewTD);
10024 handleTagNumbering(TD, S);
10025 }
Richard Smith3f1b5d02011-05-05 21:57:07 +000010026 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10027 NewND = NewTD;
10028 }
Richard Smithdda56e42011-04-15 14:24:37 +000010029
Richard Smith3cbf3f12016-07-15 20:53:25 +000010030 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +000010031 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010032 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +000010033}
10034
Richard Smithf4634362014-09-03 23:11:22 +000010035Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10036 SourceLocation AliasLoc,
10037 IdentifierInfo *Alias, CXXScopeSpec &SS,
10038 SourceLocation IdentLoc,
10039 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +000010040
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010041 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +000010042 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10043 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010044
John McCall27b18f82009-11-17 02:14:36 +000010045 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010046 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +000010047
John McCall9f3059a2009-10-09 21:13:30 +000010048 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +000010049 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +000010050 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010051 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +000010052 }
Anders Carlssonac2c9652009-03-28 06:42:02 +000010053 }
Richard Smithf4634362014-09-03 23:11:22 +000010054 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +000010055 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +000010056
10057 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +000010058 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10059 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +000010060 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +000010061
Richard Smith2b2a1762015-12-03 23:24:04 +000010062 // Check we're not shadowing a template parameter.
10063 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10064 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10065 PrevR.clear();
10066 }
Aaron Ballman43f40102014-11-14 22:34:56 +000010067
Richard Smith2b2a1762015-12-03 23:24:04 +000010068 // Filter out any other lookup result from an enclosing scope.
10069 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10070 /*AllowInlineNamespace*/false);
10071
10072 // Find the previous declaration and check that we can redeclare it.
10073 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +000010074 if (PrevR.isSingleResult()) {
10075 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10076 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010077 // We already have an alias with the same name that points to the same
10078 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +000010079 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10080 Prev = AD;
10081 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010082 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10083 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +000010084 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +000010085 << AD->getNamespace();
10086 return nullptr;
10087 }
Richard Smith2b2a1762015-12-03 23:24:04 +000010088 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +000010089 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +000010090 ? diag::err_redefinition
10091 : diag::err_redefinition_different_kind;
10092 Diag(AliasLoc, DiagID) << Alias;
10093 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10094 return nullptr;
10095 }
10096 }
Mike Stump11289f42009-09-09 15:08:12 +000010097
Nico Riecke50e59a2014-11-24 17:29:52 +000010098 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +000010099 DiagnoseUseOfDecl(ND, IdentLoc);
10100
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010101 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +000010102 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +000010103 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +000010104 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +000010105 if (Prev)
10106 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +000010107
John McCalld8d0d432010-02-16 06:53:13 +000010108 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +000010109 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +000010110}
10111
Richard Smith2246c832017-02-24 01:29:42 +000010112namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +000010113struct SpecialMemberExceptionSpecInfo
10114 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
Richard Smith2246c832017-02-24 01:29:42 +000010115 SourceLocation Loc;
10116 Sema::ImplicitExceptionSpecification ExceptSpec;
10117
Richard Smith2246c832017-02-24 01:29:42 +000010118 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10119 Sema::CXXSpecialMember CSM,
10120 Sema::InheritedConstructorInfo *ICI,
10121 SourceLocation Loc)
Richard Smith8bae1be2017-02-24 02:07:20 +000010122 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
Richard Smith2246c832017-02-24 01:29:42 +000010123
Richard Smith6f0e63e2017-02-24 21:18:47 +000010124 bool visitBase(CXXBaseSpecifier *Base);
10125 bool visitField(FieldDecl *FD);
Richard Smith2246c832017-02-24 01:29:42 +000010126
10127 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10128 unsigned Quals);
10129
10130 void visitSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +000010131 Sema::SpecialMemberOverloadResult SMOR);
Richard Smith2246c832017-02-24 01:29:42 +000010132};
10133}
10134
Richard Smith6f0e63e2017-02-24 21:18:47 +000010135bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
Richard Smith2246c832017-02-24 01:29:42 +000010136 auto *RT = Base->getType()->getAs<RecordType>();
10137 if (!RT)
Richard Smith6f0e63e2017-02-24 21:18:47 +000010138 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010139
10140 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith6f0e63e2017-02-24 21:18:47 +000010141 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10142 if (auto *BaseCtor = SMOR.getMethod()) {
10143 visitSubobjectCall(Base, BaseCtor);
10144 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010145 }
10146
10147 visitClassSubobject(BaseClass, Base, 0);
Richard Smith6f0e63e2017-02-24 21:18:47 +000010148 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010149}
10150
Richard Smith6f0e63e2017-02-24 21:18:47 +000010151bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
Richard Smith2246c832017-02-24 01:29:42 +000010152 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10153 Expr *E = FD->getInClassInitializer();
10154 if (!E)
10155 // FIXME: It's a little wasteful to build and throw away a
10156 // CXXDefaultInitExpr here.
10157 // FIXME: We should have a single context note pointing at Loc, and
10158 // this location should be MD->getLocation() instead, since that's
10159 // the location where we actually use the default init expression.
10160 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10161 if (E)
10162 ExceptSpec.CalledExpr(E);
10163 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10164 ->getAs<RecordType>()) {
10165 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10166 FD->getType().getCVRQualifiers());
10167 }
Richard Smith6f0e63e2017-02-24 21:18:47 +000010168 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010169}
10170
10171void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10172 Subobject Subobj,
10173 unsigned Quals) {
10174 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10175 bool IsMutable = Field && Field->isMutable();
10176 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10177}
10178
10179void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +000010180 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
Richard Smith2246c832017-02-24 01:29:42 +000010181 // Note, if lookup fails, it doesn't matter what exception specification we
10182 // choose because the special member will be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +000010183 if (CXXMethodDecl *MD = SMOR.getMethod())
10184 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
Richard Smith2246c832017-02-24 01:29:42 +000010185}
10186
10187static Sema::ImplicitExceptionSpecification
10188ComputeDefaultedSpecialMemberExceptionSpec(
10189 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10190 Sema::InheritedConstructorInfo *ICI) {
Richard Smithd3b5c9082012-07-27 04:22:15 +000010191 CXXRecordDecl *ClassDecl = MD->getParent();
10192
Douglas Gregor6d880b12010-07-01 22:31:05 +000010193 // C++ [except.spec]p14:
10194 // An implicitly declared special member function (Clause 12) shall have an
10195 // exception-specification. [...]
Richard Smith2246c832017-02-24 01:29:42 +000010196 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010197 if (ClassDecl->isInvalidDecl())
Richard Smith2246c832017-02-24 01:29:42 +000010198 return Info.ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +000010199
Richard Smith6f0e63e2017-02-24 21:18:47 +000010200 // C++1z [except.spec]p7:
10201 // [Look for exceptions thrown by] a constructor selected [...] to
10202 // initialize a potentially constructed subobject,
10203 // C++1z [except.spec]p8:
10204 // The exception specification for an implicitly-declared destructor, or a
10205 // destructor without a noexcept-specifier, is potentially-throwing if and
10206 // only if any of the destructors for any of its potentially constructed
10207 // subojects is potentially throwing.
Richard Smithdf054d32017-02-25 23:53:05 +000010208 // FIXME: We respect the first rule but ignore the "potentially constructed"
10209 // in the second rule to resolve a core issue (no number yet) that would have
10210 // us reject:
Richard Smith6f0e63e2017-02-24 21:18:47 +000010211 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10212 // struct B : A {};
10213 // struct C : B { void f(); };
10214 // ... due to giving B::~B() a non-throwing exception specification.
Richard Smithdf054d32017-02-25 23:53:05 +000010215 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10216 : Info.VisitAllBases);
John McCalldb40c7f2010-12-14 08:05:40 +000010217
Richard Smith2246c832017-02-24 01:29:42 +000010218 return Info.ExceptSpec;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010219}
10220
Richard Smith8bf22e52012-11-29 01:34:07 +000010221namespace {
10222/// RAII object to register a special member as being currently declared.
10223struct DeclaringSpecialMember {
10224 Sema &S;
10225 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +000010226 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +000010227 bool WasAlreadyBeingDeclared;
10228
10229 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith13381222017-02-23 21:43:43 +000010230 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +000010231 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +000010232 if (WasAlreadyBeingDeclared)
10233 // This almost never happens, but if it does, ensure that our cache
10234 // doesn't contain a stale result.
10235 S.SpecialMemberCache.clear();
Richard Smith13381222017-02-23 21:43:43 +000010236 else {
10237 // Register a note to be produced if we encounter an error while
10238 // declaring the special member.
10239 Sema::CodeSynthesisContext Ctx;
10240 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10241 // FIXME: We don't have a location to use here. Using the class's
10242 // location maintains the fiction that we declare all special members
10243 // with the class, but (1) it's not clear that lying about that helps our
10244 // users understand what's going on, and (2) there may be outer contexts
10245 // on the stack (some of which are relevant) and printing them exposes
10246 // our lies.
10247 Ctx.PointOfInstantiation = RD->getLocation();
10248 Ctx.Entity = RD;
10249 Ctx.SpecialMember = CSM;
10250 S.pushCodeSynthesisContext(Ctx);
10251 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010252 }
10253 ~DeclaringSpecialMember() {
Richard Smith13381222017-02-23 21:43:43 +000010254 if (!WasAlreadyBeingDeclared) {
Richard Smith8bf22e52012-11-29 01:34:07 +000010255 S.SpecialMembersBeingDeclared.erase(D);
Richard Smith13381222017-02-23 21:43:43 +000010256 S.popCodeSynthesisContext();
10257 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010258 }
10259
10260 /// \brief Are we already trying to declare this special member?
10261 bool isAlreadyBeingDeclared() const {
10262 return WasAlreadyBeingDeclared;
10263 }
10264};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010265}
Richard Smith8bf22e52012-11-29 01:34:07 +000010266
Richard Smith12e79312016-05-13 06:47:56 +000010267void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10268 // Look up any existing declarations, but don't trigger declaration of all
10269 // implicit special members with this name.
10270 DeclarationName Name = FD->getDeclName();
10271 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10272 ForRedeclaration);
10273 for (auto *D : FD->getParent()->lookup(Name))
10274 if (auto *Acceptable = R.getAcceptableDecl(D))
10275 R.addDecl(Acceptable);
10276 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +000010277 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +000010278
Richard Smithf445f192017-02-09 21:04:43 +000010279 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
Richard Smith12e79312016-05-13 06:47:56 +000010280}
10281
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010282CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10283 CXXRecordDecl *ClassDecl) {
10284 // C++ [class.ctor]p5:
10285 // A default constructor for a class X is a constructor of class X
10286 // that can be called without an argument. If there is no
10287 // user-declared constructor for class X, a default constructor is
10288 // implicitly declared. An implicitly-declared default constructor
10289 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010290 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010291 "Should not build implicit default constructor!");
10292
Richard Smith8bf22e52012-11-29 01:34:07 +000010293 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10294 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010295 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010296
Richard Smithb5800092012-06-10 05:43:50 +000010297 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10298 CXXDefaultConstructor,
10299 false);
10300
Douglas Gregor6d880b12010-07-01 22:31:05 +000010301 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010302 CanQualType ClassType
10303 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010304 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010305 DeclarationName Name
10306 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010307 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +000010308 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010309 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10310 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10311 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010312 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +000010313 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010314
10315 if (getLangOpts().CUDA) {
10316 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10317 DefaultCon,
10318 /* ConstRHS */ false,
10319 /* Diagnose */ false);
10320 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010321
10322 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010323 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010324 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010325
Richard Smith6b02d462012-12-08 08:32:28 +000010326 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10327 // constructors is easy to compute.
10328 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10329
Douglas Gregor9672f922010-07-03 00:47:00 +000010330 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +000010331 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +000010332
Richard Smith12e79312016-05-13 06:47:56 +000010333 Scope *S = getScopeForContext(ClassDecl);
10334 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10335
10336 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10337 SetDeclDeleted(DefaultCon, ClassLoc);
10338
10339 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +000010340 PushOnScopeChains(DefaultCon, S, false);
10341 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +000010342
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010343 return DefaultCon;
10344}
10345
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010346void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10347 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010348 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010349 !Constructor->doesThisDeclarationHaveABody() &&
10350 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010351 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010352
Anders Carlsson423f5d82010-04-23 16:04:08 +000010353 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010354 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010355
Eli Friedmaneaf34142012-10-18 20:14:08 +000010356 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010357 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +000010358 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010359 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010360 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +000010361 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +000010362 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +000010363 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +000010364 }
Douglas Gregor73193272010-09-20 16:48:21 +000010365
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010366 // The exception specification is needed because we are defining the
10367 // function.
10368 ResolveExceptionSpec(CurrentLocation,
10369 Constructor->getType()->castAs<FunctionProtoType>());
10370
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010371 SourceLocation Loc = Constructor->getLocEnd().isValid()
10372 ? Constructor->getLocEnd()
10373 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010374 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010375
Eli Friedman276dd182013-09-05 00:02:25 +000010376 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010377 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010378
10379 if (ASTMutationListener *L = getASTMutationListener()) {
10380 L->CompletedImplicitDefinition(Constructor);
10381 }
Richard Trieuef64e942013-10-25 00:56:00 +000010382
10383 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010384}
10385
Richard Smith938f40b2011-06-11 17:19:42 +000010386void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010387 // Perform any delayed checks on exception specifications.
10388 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010389}
10390
Richard Smith5179eb72016-06-28 19:03:57 +000010391/// Find or create the fake constructor we synthesize to model constructing an
10392/// object of a derived class via a constructor of a base class.
10393CXXConstructorDecl *
10394Sema::findInheritingConstructor(SourceLocation Loc,
10395 CXXConstructorDecl *BaseCtor,
10396 ConstructorUsingShadowDecl *Shadow) {
10397 CXXRecordDecl *Derived = Shadow->getParent();
10398 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010399
Richard Smith5179eb72016-06-28 19:03:57 +000010400 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10401 // For now we use the name of the base class constructor as a member of the
10402 // derived class to indicate a (fake) inherited constructor name.
10403 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010404
Richard Smith5179eb72016-06-28 19:03:57 +000010405 // Check to see if we already have a fake constructor for this inherited
10406 // constructor call.
10407 for (NamedDecl *Ctor : Derived->lookup(Name))
10408 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10409 ->getInheritedConstructor()
10410 .getConstructor(),
10411 BaseCtor))
10412 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010413
Richard Smith5179eb72016-06-28 19:03:57 +000010414 DeclarationNameInfo NameInfo(Name, UsingLoc);
10415 TypeSourceInfo *TInfo =
10416 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10417 FunctionProtoTypeLoc ProtoLoc =
10418 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010419
Richard Smith5179eb72016-06-28 19:03:57 +000010420 // Check the inherited constructor is valid and find the list of base classes
10421 // from which it was inherited.
10422 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010423
Richard Smith5179eb72016-06-28 19:03:57 +000010424 bool Constexpr =
10425 BaseCtor->isConstexpr() &&
10426 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10427 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010428
Richard Smith5179eb72016-06-28 19:03:57 +000010429 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10430 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10431 BaseCtor->isExplicit(), /*Inline=*/true,
10432 /*ImplicitlyDeclared=*/true, Constexpr,
10433 InheritedConstructor(Shadow, BaseCtor));
10434 if (Shadow->isInvalidDecl())
10435 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010436
Richard Smith5179eb72016-06-28 19:03:57 +000010437 // Build an unevaluated exception specification for this fake constructor.
10438 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10439 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10440 EPI.ExceptionSpec.Type = EST_Unevaluated;
10441 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10442 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10443 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010444
Richard Smith5179eb72016-06-28 19:03:57 +000010445 // Build the parameter declarations.
10446 SmallVector<ParmVarDecl *, 16> ParamDecls;
10447 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010448 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010449 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10450 ParmVarDecl *PD = ParmVarDecl::Create(
10451 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10452 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10453 PD->setScopeInfo(0, I);
10454 PD->setImplicit();
10455 // Ensure attributes are propagated onto parameters (this matters for
10456 // format, pass_object_size, ...).
10457 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10458 ParamDecls.push_back(PD);
10459 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010460 }
10461
Richard Smith5179eb72016-06-28 19:03:57 +000010462 // Set up the new constructor.
10463 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10464 DerivedCtor->setAccess(BaseCtor->getAccess());
10465 DerivedCtor->setParams(ParamDecls);
10466 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010467
10468 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10469 SetDeclDeleted(DerivedCtor, UsingLoc);
10470
Richard Smith5179eb72016-06-28 19:03:57 +000010471 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010472}
10473
Richard Smith80a47022016-06-29 01:10:27 +000010474void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10475 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10476 Ctor->getInheritedConstructor().getShadowDecl());
10477 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10478 /*Diagnose*/true);
10479}
10480
Richard Smithc2bc61b2013-03-18 21:12:30 +000010481void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10482 CXXConstructorDecl *Constructor) {
10483 CXXRecordDecl *ClassDecl = Constructor->getParent();
10484 assert(Constructor->getInheritedConstructor() &&
10485 !Constructor->doesThisDeclarationHaveABody() &&
10486 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010487 if (Constructor->isInvalidDecl())
10488 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010489
Richard Smith5179eb72016-06-28 19:03:57 +000010490 ConstructorUsingShadowDecl *Shadow =
10491 Constructor->getInheritedConstructor().getShadowDecl();
10492 CXXConstructorDecl *InheritedCtor =
10493 Constructor->getInheritedConstructor().getConstructor();
10494
10495 // [class.inhctor.init]p1:
10496 // initialization proceeds as if a defaulted default constructor is used to
10497 // initialize the D object and each base class subobject from which the
10498 // constructor was inherited
10499
10500 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10501 CXXRecordDecl *RD = Shadow->getParent();
10502 SourceLocation InitLoc = Shadow->getLocation();
10503
10504 // Initializations are performed "as if by a defaulted default constructor",
10505 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010506 SynthesizedFunctionScope Scope(*this, Constructor);
10507 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010508
10509 // Build explicit initializers for all base classes from which the
10510 // constructor was inherited.
10511 SmallVector<CXXCtorInitializer*, 8> Inits;
10512 for (bool VBase : {false, true}) {
10513 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10514 if (B.isVirtual() != VBase)
10515 continue;
10516
10517 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10518 if (!BaseRD)
10519 continue;
10520
10521 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10522 if (!BaseCtor.first)
10523 continue;
10524
10525 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10526 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10527 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10528
10529 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10530 Inits.push_back(new (Context) CXXCtorInitializer(
10531 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10532 SourceLocation()));
10533 }
10534 }
10535
10536 // We now proceed as if for a defaulted default constructor, with the relevant
10537 // initializers replaced.
10538
10539 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10540 if (HadError || Trap.hasErrorOccurred()) {
10541 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010542 Constructor->setInvalidDecl();
10543 return;
10544 }
10545
Richard Smith5179eb72016-06-28 19:03:57 +000010546 // The exception specification is needed because we are defining the
10547 // function.
10548 ResolveExceptionSpec(CurrentLocation,
10549 Constructor->getType()->castAs<FunctionProtoType>());
10550
10551 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010552
Eli Friedman276dd182013-09-05 00:02:25 +000010553 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010554 MarkVTableUsed(CurrentLocation, ClassDecl);
10555
10556 if (ASTMutationListener *L = getASTMutationListener()) {
10557 L->CompletedImplicitDefinition(Constructor);
10558 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010559
Richard Smith5179eb72016-06-28 19:03:57 +000010560 DiagnoseUninitializedFields(*this, Constructor);
10561}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010562
Alexis Huntf91729462011-05-12 22:46:25 +000010563CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10564 // C++ [class.dtor]p2:
10565 // If a class has no user-declared destructor, a destructor is
10566 // declared implicitly. An implicitly-declared destructor is an
10567 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010568 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010569
Richard Smith8bf22e52012-11-29 01:34:07 +000010570 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10571 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010572 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010573
Douglas Gregor7454c562010-07-02 20:37:36 +000010574 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010575 CanQualType ClassType
10576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010577 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010578 DeclarationName Name
10579 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010580 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010581 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010582 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010583 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010584 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010585 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010586 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010587
10588 if (getLangOpts().CUDA) {
10589 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10590 Destructor,
10591 /* ConstRHS */ false,
10592 /* Diagnose */ false);
10593 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010594
10595 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010596 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010597 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010598
Richard Smith6b02d462012-12-08 08:32:28 +000010599 // We don't need to use SpecialMemberIsTrivial here; triviality for
10600 // destructors is easy to compute.
10601 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10602
Douglas Gregor7454c562010-07-02 20:37:36 +000010603 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010604 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010605
Richard Smith12e79312016-05-13 06:47:56 +000010606 Scope *S = getScopeForContext(ClassDecl);
10607 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10608
Richard Smithb2f0f052016-10-10 18:54:32 +000010609 // We can't check whether an implicit destructor is deleted before we complete
10610 // the definition of the class, because its validity depends on the alignment
10611 // of the class. We'll check this from ActOnFields once the class is complete.
10612 if (ClassDecl->isCompleteDefinition() &&
10613 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010614 SetDeclDeleted(Destructor, ClassLoc);
10615
Douglas Gregor7454c562010-07-02 20:37:36 +000010616 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010617 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010618 PushOnScopeChains(Destructor, S, false);
10619 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010620
Douglas Gregorf1203042010-07-01 19:09:28 +000010621 return Destructor;
10622}
10623
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010624void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010625 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010626 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010627 !Destructor->doesThisDeclarationHaveABody() &&
10628 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010629 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010630 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010631 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010632
Douglas Gregor54818f02010-05-12 16:39:35 +000010633 if (Destructor->isInvalidDecl())
10634 return;
10635
Eli Friedmaneaf34142012-10-18 20:14:08 +000010636 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010637
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010638 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010639 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10640 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010641
Douglas Gregor54818f02010-05-12 16:39:35 +000010642 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010643 Diag(CurrentLocation, diag::note_member_synthesized_at)
10644 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10645
10646 Destructor->setInvalidDecl();
10647 return;
10648 }
10649
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010650 // The exception specification is needed because we are defining the
10651 // function.
10652 ResolveExceptionSpec(CurrentLocation,
10653 Destructor->getType()->castAs<FunctionProtoType>());
10654
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010655 SourceLocation Loc = Destructor->getLocEnd().isValid()
10656 ? Destructor->getLocEnd()
10657 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010658 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010659 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010660 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010661
10662 if (ASTMutationListener *L = getASTMutationListener()) {
10663 L->CompletedImplicitDefinition(Destructor);
10664 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010665}
10666
Richard Smith84973e52012-04-21 18:42:51 +000010667/// \brief Perform any semantic analysis which needs to be delayed until all
10668/// pending class member declarations have been parsed.
10669void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010670 // If the context is an invalid C++ class, just suppress these checks.
10671 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10672 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010673 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010674 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010675 return;
10676 }
Reid Kleckner61195e12017-01-05 01:08:22 +000010677 checkForMultipleExportedDefaultConstructors(*this, Record);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010678 }
10679}
10680
Hans Wennborg99000c22015-08-15 01:18:16 +000010681void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Kleckner5b640342016-02-26 19:51:02 +000010682 referenceDLLExportedClassMethods();
10683}
10684
10685void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010686 if (!DelayedDllExportClasses.empty()) {
10687 // Calling ReferenceDllExportedMethods might cause the current function to
10688 // be called again, so use a local copy of DelayedDllExportClasses.
10689 SmallVector<CXXRecordDecl *, 4> WorkList;
10690 std::swap(DelayedDllExportClasses, WorkList);
10691 for (CXXRecordDecl *Class : WorkList)
10692 ReferenceDllExportedMethods(*this, Class);
10693 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010694}
10695
Richard Smithd3b5c9082012-07-27 04:22:15 +000010696void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10697 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010698 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010699 "adjusting dtor exception specs was introduced in c++11");
10700
Sebastian Redl623ea822011-05-19 05:13:44 +000010701 // C++11 [class.dtor]p3:
10702 // A declaration of a destructor that does not have an exception-
10703 // specification is implicitly considered to have the same exception-
10704 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010705 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010706 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010707 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010708 return;
10709
Chandler Carruth9a797572011-09-20 04:55:26 +000010710 // Replace the destructor's type, building off the existing one. Fortunately,
10711 // the only thing of interest in the destructor type is its extended info.
10712 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010713 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010714 EPI.ExceptionSpec.Type = EST_Unevaluated;
10715 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010716 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010717
Sebastian Redl623ea822011-05-19 05:13:44 +000010718 // FIXME: If the destructor has a body that could throw, and the newly created
10719 // spec doesn't allow exceptions, we should emit a warning, because this
10720 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010721 // However, we don't have a body or an exception specification yet, so it
10722 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010723}
10724
Pavel Labath58934982013-08-30 08:52:28 +000010725namespace {
10726/// \brief An abstract base class for all helper classes used in building the
10727// copy/move operators. These classes serve as factory functions and help us
10728// avoid using the same Expr* in the AST twice.
10729class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010730 ExprBuilder(const ExprBuilder&) = delete;
10731 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010732
10733protected:
10734 static Expr *assertNotNull(Expr *E) {
10735 assert(E && "Expression construction must not fail.");
10736 return E;
10737 }
10738
10739public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010740 ExprBuilder() {}
10741 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010742
10743 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10744};
10745
10746class RefBuilder: public ExprBuilder {
10747 VarDecl *Var;
10748 QualType VarType;
10749
10750public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010751 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010752 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010753 }
10754
10755 RefBuilder(VarDecl *Var, QualType VarType)
10756 : Var(Var), VarType(VarType) {}
10757};
10758
10759class ThisBuilder: public ExprBuilder {
10760public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010761 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010762 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010763 }
10764};
10765
10766class CastBuilder: public ExprBuilder {
10767 const ExprBuilder &Builder;
10768 QualType Type;
10769 ExprValueKind Kind;
10770 const CXXCastPath &Path;
10771
10772public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010773 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010774 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10775 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010776 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010777 }
10778
10779 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10780 const CXXCastPath &Path)
10781 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10782};
10783
10784class DerefBuilder: public ExprBuilder {
10785 const ExprBuilder &Builder;
10786
10787public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010788 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010789 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010790 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010791 }
10792
10793 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10794};
10795
10796class MemberBuilder: public ExprBuilder {
10797 const ExprBuilder &Builder;
10798 QualType Type;
10799 CXXScopeSpec SS;
10800 bool IsArrow;
10801 LookupResult &MemberLookup;
10802
10803public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010804 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010805 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010806 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010807 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010808 }
10809
10810 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10811 LookupResult &MemberLookup)
10812 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10813 MemberLookup(MemberLookup) {}
10814};
10815
10816class MoveCastBuilder: public ExprBuilder {
10817 const ExprBuilder &Builder;
10818
10819public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010820 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010821 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10822 }
10823
10824 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10825};
10826
10827class LvalueConvBuilder: public ExprBuilder {
10828 const ExprBuilder &Builder;
10829
10830public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010831 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010832 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010833 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010834 }
10835
10836 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10837};
10838
10839class SubscriptBuilder: public ExprBuilder {
10840 const ExprBuilder &Base;
10841 const ExprBuilder &Index;
10842
10843public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010844 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010845 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010846 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010847 }
10848
10849 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10850 : Base(Base), Index(Index) {}
10851};
10852
10853} // end anonymous namespace
10854
Richard Smith41ae3282012-11-14 00:50:40 +000010855/// When generating a defaulted copy or move assignment operator, if a field
10856/// should be copied with __builtin_memcpy rather than via explicit assignments,
10857/// do so. This optimization only applies for arrays of scalars, and for arrays
10858/// of class type where the selected copy/move-assignment operator is trivial.
10859static StmtResult
10860buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010861 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010862 // Compute the size of the memory buffer to be copied.
10863 QualType SizeType = S.Context.getSizeType();
10864 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10865 S.Context.getTypeSizeInChars(T).getQuantity());
10866
10867 // Take the address of the field references for "from" and "to". We
10868 // directly construct UnaryOperators here because semantic analysis
10869 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010870 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010871 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10872 S.Context.getPointerType(From->getType()),
10873 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010874 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010875 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10876 S.Context.getPointerType(To->getType()),
10877 VK_RValue, OK_Ordinary, Loc);
10878
10879 const Type *E = T->getBaseElementTypeUnsafe();
10880 bool NeedsCollectableMemCpy =
10881 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10882
10883 // Create a reference to the __builtin_objc_memmove_collectable function
10884 StringRef MemCpyName = NeedsCollectableMemCpy ?
10885 "__builtin_objc_memmove_collectable" :
10886 "__builtin_memcpy";
10887 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10888 Sema::LookupOrdinaryName);
10889 S.LookupName(R, S.TUScope, true);
10890
10891 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10892 if (!MemCpy)
10893 // Something went horribly wrong earlier, and we will have complained
10894 // about it.
10895 return StmtError();
10896
10897 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010898 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010899 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10900
10901 Expr *CallArgs[] = {
10902 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10903 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010904 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010905 Loc, CallArgs, Loc);
10906
10907 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010908 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010909}
10910
Sebastian Redl22653ba2011-08-30 19:58:05 +000010911/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010912/// \c To.
10913///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010914/// This routine is used to copy/move the members of a class with an
10915/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010916/// copied are arrays, this routine builds for loops to copy them.
10917///
10918/// \param S The Sema object used for type-checking.
10919///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010920/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010921///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010922/// \param T The type of the expressions being copied/moved. Both expressions
10923/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010924///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010925/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010926///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010927/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010928///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010929/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010930/// Otherwise, it's a non-static member subobject.
10931///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010932/// \param Copying Whether we're copying or moving.
10933///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010934/// \param Depth Internal parameter recording the depth of the recursion.
10935///
Richard Smith41ae3282012-11-14 00:50:40 +000010936/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10937/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010938static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010939buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010940 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010941 bool CopyingBaseSubobject, bool Copying,
10942 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010943 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010944 // Each subobject is assigned in the manner appropriate to its type:
10945 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010946 // - if the subobject is of class type, as if by a call to operator= with
10947 // the subobject as the object expression and the corresponding
10948 // subobject of x as a single function argument (as if by explicit
10949 // qualification; that is, ignoring any possible virtual overriding
10950 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010951 //
10952 // C++03 [class.copy]p13:
10953 // - if the subobject is of class type, the copy assignment operator for
10954 // the class is used (as if by explicit qualification; that is,
10955 // ignoring any possible virtual overriding functions in more derived
10956 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010957 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010959
Douglas Gregorb139cd52010-05-01 20:49:11 +000010960 // Look for operator=.
10961 DeclarationName Name
10962 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10963 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10964 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010965
Richard Smith52c0b582012-11-13 00:54:12 +000010966 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10967 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010968 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010969 LookupResult::Filter F = OpLookup.makeFilter();
10970 while (F.hasNext()) {
10971 NamedDecl *D = F.next();
10972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10973 if (Method->isCopyAssignmentOperator() ||
10974 (!Copying && Method->isMoveAssignmentOperator()))
10975 continue;
10976
10977 F.erase();
10978 }
10979 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010980 }
Richard Smith52c0b582012-11-13 00:54:12 +000010981
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010982 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010983 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010984 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010985 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010986 // ambiguities), we need to cast "this" to that subobject type; to
10987 // ensure that we don't go through the virtual call mechanism, we need
10988 // to qualify the operator= name with the base class (see below). However,
10989 // this means that if the base class has a protected copy assignment
10990 // operator, the protected member access check will fail. So, we
10991 // rewrite "protected" access to "public" access in this case, since we
10992 // know by construction that we're calling from a derived class.
10993 if (CopyingBaseSubobject) {
10994 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10995 L != LEnd; ++L) {
10996 if (L.getAccess() == AS_protected)
10997 L.setAccess(AS_public);
10998 }
10999 }
Richard Smith52c0b582012-11-13 00:54:12 +000011000
Douglas Gregorb139cd52010-05-01 20:49:11 +000011001 // Create the nested-name-specifier that will be used to qualify the
11002 // reference to operator=; this is required to suppress the virtual
11003 // call mechanism.
11004 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000011005 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000011006 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000011007 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000011008 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000011009 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000011010
Douglas Gregorb139cd52010-05-01 20:49:11 +000011011 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000011012 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000011013 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11014 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011015 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000011016 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011017 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011018 /*SuppressQualifierCheck=*/true);
11019 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011020 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011021
Douglas Gregorb139cd52010-05-01 20:49:11 +000011022 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000011023
Pavel Labath58934982013-08-30 08:52:28 +000011024 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000011025 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011026 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000011027 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011028 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011029 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011030
Richard Smith41ae3282012-11-14 00:50:40 +000011031 // If we built a call to a trivial 'operator=' while copying an array,
11032 // bail out. We'll replace the whole shebang with a memcpy.
11033 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11034 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000011035 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000011036
Richard Smith52c0b582012-11-13 00:54:12 +000011037 // Convert to an expression-statement, and clean up any produced
11038 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000011039 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011040 }
John McCallab8c2732010-03-16 06:11:48 +000011041
Richard Smith52c0b582012-11-13 00:54:12 +000011042 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000011043 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000011044 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011045 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000011046 ExprResult Assignment = S.CreateBuiltinBinOp(
11047 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011048 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011049 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000011050 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011051 }
Richard Smith52c0b582012-11-13 00:54:12 +000011052
11053 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000011054 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000011055
Douglas Gregorb139cd52010-05-01 20:49:11 +000011056 // Construct a loop over the array bounds, e.g.,
11057 //
11058 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11059 //
11060 // that will copy each of the array elements.
11061 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000011062
Douglas Gregorb139cd52010-05-01 20:49:11 +000011063 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000011064 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011065 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000011066 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011067 llvm::raw_svector_ostream OS(Str);
11068 OS << "__i" << Depth;
11069 IterationVarName = &S.Context.Idents.get(OS.str());
11070 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000011071 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011072 IterationVarName, SizeType,
11073 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011074 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000011075
Douglas Gregorb139cd52010-05-01 20:49:11 +000011076 // Initialize the iteration variable to zero.
11077 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011078 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011079
Pavel Labath58934982013-08-30 08:52:28 +000011080 // Creates a reference to the iteration variable.
11081 RefBuilder IterationVarRef(IterationVar, SizeType);
11082 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000011083
Douglas Gregorb139cd52010-05-01 20:49:11 +000011084 // Create the DeclStmt that holds the iteration variable.
11085 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011086
Douglas Gregorb139cd52010-05-01 20:49:11 +000011087 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000011088 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11089 MoveCastBuilder FromIndexMove(FromIndexCopy);
11090 const ExprBuilder *FromIndex;
11091 if (Copying)
11092 FromIndex = &FromIndexCopy;
11093 else
11094 FromIndex = &FromIndexMove;
11095
11096 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011097
11098 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000011099 StmtResult Copy =
11100 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000011101 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000011102 Copying, Depth + 1);
11103 // Bail out if copying fails or if we determined that we should use memcpy.
11104 if (Copy.isInvalid() || !Copy.get())
11105 return Copy;
11106
11107 // Create the comparison against the array bound.
11108 llvm::APInt Upper
11109 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11110 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000011111 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000011112 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11113 BO_NE, S.Context.BoolTy,
Adam Nemet484aa452017-03-27 19:17:25 +000011114 VK_RValue, OK_Ordinary, Loc, FPOptions());
Richard Smith41ae3282012-11-14 00:50:40 +000011115
11116 // Create the pre-increment of the iteration variable.
11117 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000011118 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11119 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011120
Douglas Gregorb139cd52010-05-01 20:49:11 +000011121 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000011122 return S.ActOnForStmt(
11123 Loc, Loc, InitStmt,
11124 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11125 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011126}
11127
Richard Smith41ae3282012-11-14 00:50:40 +000011128static StmtResult
11129buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000011130 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000011131 bool CopyingBaseSubobject, bool Copying) {
11132 // Maybe we should use a memcpy?
11133 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11134 T.isTriviallyCopyableType(S.Context))
11135 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11136
11137 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11138 CopyingBaseSubobject,
11139 Copying, 0));
11140
11141 // If we ended up picking a trivial assignment operator for an array of a
11142 // non-trivially-copyable class type, just emit a memcpy.
11143 if (!Result.isInvalid() && !Result.get())
11144 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11145
11146 return Result;
11147}
11148
Alexis Hunt119f3652011-05-14 05:23:20 +000011149CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11150 // Note: The following rules are largely analoguous to the copy
11151 // constructor rules. Note that virtual bases are not taken into account
11152 // for determining the argument type of the operator. Note also that
11153 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000011154 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000011155
Richard Smith8bf22e52012-11-29 01:34:07 +000011156 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11157 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011158 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011159
Alexis Hunt119f3652011-05-14 05:23:20 +000011160 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11161 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000011162 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11163 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000011164 ArgType = ArgType.withConst();
11165 ArgType = Context.getLValueReferenceType(ArgType);
11166
Richard Smith99005e62013-05-07 03:19:20 +000011167 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11168 CXXCopyAssignment,
11169 Const);
11170
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011171 // An implicitly-declared copy assignment operator is an inline public
11172 // member of its class.
11173 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000011174 SourceLocation ClassLoc = ClassDecl->getLocation();
11175 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011176 CXXMethodDecl *CopyAssignment =
11177 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011178 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11179 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011180 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000011181 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011182 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011183
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011184 if (getLangOpts().CUDA) {
11185 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11186 CopyAssignment,
11187 /* ConstRHS */ Const,
11188 /* Diagnose */ false);
11189 }
11190
Richard Smithd3b5c9082012-07-27 04:22:15 +000011191 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011192 FunctionProtoType::ExtProtoInfo EPI =
11193 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011194 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011195
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011196 // Add the parameter to the operator.
11197 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011198 ClassLoc, ClassLoc,
11199 /*Id=*/nullptr, ArgType,
11200 /*TInfo=*/nullptr, SC_None,
11201 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011202 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011203
Richard Smith6b02d462012-12-08 08:32:28 +000011204 CopyAssignment->setTrivial(
11205 ClassDecl->needsOverloadResolutionForCopyAssignment()
11206 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11207 : ClassDecl->hasTrivialCopyAssignment());
11208
Richard Smith6b02d462012-12-08 08:32:28 +000011209 // Note that we have added this copy-assignment operator.
11210 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11211
Richard Smith12e79312016-05-13 06:47:56 +000011212 Scope *S = getScopeForContext(ClassDecl);
11213 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11214
11215 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11216 SetDeclDeleted(CopyAssignment, ClassLoc);
11217
11218 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011219 PushOnScopeChains(CopyAssignment, S, false);
11220 ClassDecl->addDecl(CopyAssignment);
11221
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011222 return CopyAssignment;
11223}
11224
Richard Smithd577fbb2013-06-13 03:23:42 +000011225/// Diagnose an implicit copy operation for a class which is odr-used, but
11226/// which is deprecated because the class has a user-declared copy constructor,
11227/// copy assignment operator, or destructor.
11228static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11229 SourceLocation UseLoc) {
11230 assert(CopyOp->isImplicit());
11231
11232 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011233 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011234
11235 // In Microsoft mode, assignment operations don't affect constructors and
11236 // vice versa.
11237 if (RD->hasUserDeclaredDestructor()) {
11238 UserDeclaredOperation = RD->getDestructor();
11239 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11240 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011241 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011242 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011243 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011244 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011245 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011246 break;
11247 }
11248 }
11249 assert(UserDeclaredOperation);
11250 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11251 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011252 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011253 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011254 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011255 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011256 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011257 break;
11258 }
11259 }
11260 assert(UserDeclaredOperation);
11261 }
11262
11263 if (UserDeclaredOperation) {
11264 S.Diag(UserDeclaredOperation->getLocation(),
11265 diag::warn_deprecated_copy_operation)
11266 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11267 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11268 S.Diag(UseLoc, diag::note_member_synthesized_at)
11269 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11270 : Sema::CXXCopyAssignment)
11271 << RD;
11272 }
11273}
11274
Douglas Gregorb139cd52010-05-01 20:49:11 +000011275void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11276 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011277 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011278 CopyAssignOperator->isOverloadedOperator() &&
11279 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011280 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11281 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011282 "DefineImplicitCopyAssignment called for wrong function");
11283
11284 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11285
11286 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11287 CopyAssignOperator->setInvalidDecl();
11288 return;
11289 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011290
11291 // C++11 [class.copy]p18:
11292 // The [definition of an implicitly declared copy assignment operator] is
11293 // deprecated if the class has a user-declared copy constructor or a
11294 // user-declared destructor.
11295 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11296 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11297
Eli Friedman276dd182013-09-05 00:02:25 +000011298 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011299
Eli Friedmaneaf34142012-10-18 20:14:08 +000011300 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011301 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011302
11303 // C++0x [class.copy]p30:
11304 // The implicitly-defined or explicitly-defaulted copy assignment operator
11305 // for a non-union class X performs memberwise copy assignment of its
11306 // subobjects. The direct base classes of X are assigned first, in the
11307 // order of their declaration in the base-specifier-list, and then the
11308 // immediate non-static data members of X are assigned, in the order in
11309 // which they were declared in the class definition.
11310
11311 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011312 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011313
11314 // The parameter for the "other" object, which we are copying from.
11315 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11316 Qualifiers OtherQuals = Other->getType().getQualifiers();
11317 QualType OtherRefType = Other->getType();
11318 if (const LValueReferenceType *OtherRef
11319 = OtherRefType->getAs<LValueReferenceType>()) {
11320 OtherRefType = OtherRef->getPointeeType();
11321 OtherQuals = OtherRefType.getQualifiers();
11322 }
11323
11324 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011325 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11326 ? CopyAssignOperator->getLocEnd()
11327 : CopyAssignOperator->getLocation();
11328
Pavel Labath58934982013-08-30 08:52:28 +000011329 // Builds a DeclRefExpr for the "other" object.
11330 RefBuilder OtherRef(Other, OtherRefType);
11331
11332 // Builds the "this" pointer.
11333 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011334
11335 // Assign base classes.
11336 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011337 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011338 // Form the assignment:
11339 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011340 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011341 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011342 Invalid = true;
11343 continue;
11344 }
11345
John McCallcf142162010-08-07 06:22:56 +000011346 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011347 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011348
Douglas Gregorb139cd52010-05-01 20:49:11 +000011349 // Construct the "from" expression, which is an implicit cast to the
11350 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011351 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11352 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011353
11354 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011355 DerefBuilder DerefThis(This);
11356 CastBuilder To(DerefThis,
11357 Context.getCVRQualifiedType(
11358 BaseType, CopyAssignOperator->getTypeQualifiers()),
11359 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011360
11361 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011362 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011363 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011364 /*CopyingBaseSubobject=*/true,
11365 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011366 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011367 Diag(CurrentLocation, diag::note_member_synthesized_at)
11368 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11369 CopyAssignOperator->setInvalidDecl();
11370 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011371 }
11372
11373 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011374 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011375 }
11376
Douglas Gregorb139cd52010-05-01 20:49:11 +000011377 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011378 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011379 // FIXME: We should form some kind of AST representation for the implied
11380 // memcpy in a union copy operation.
11381 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011382 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011383
11384 if (Field->isInvalidDecl()) {
11385 Invalid = true;
11386 continue;
11387 }
11388
Douglas Gregorb139cd52010-05-01 20:49:11 +000011389 // Check for members of reference type; we can't copy those.
11390 if (Field->getType()->isReferenceType()) {
11391 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11392 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11393 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011394 Diag(CurrentLocation, diag::note_member_synthesized_at)
11395 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011396 Invalid = true;
11397 continue;
11398 }
11399
11400 // Check for members of const-qualified, non-class type.
11401 QualType BaseType = Context.getBaseElementType(Field->getType());
11402 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11403 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11404 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11405 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011406 Diag(CurrentLocation, diag::note_member_synthesized_at)
11407 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011408 Invalid = true;
11409 continue;
11410 }
John McCall1b1a1db2011-06-17 00:18:42 +000011411
11412 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011413 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11414 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011415
11416 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011417 if (FieldType->isIncompleteArrayType()) {
11418 assert(ClassDecl->hasFlexibleArrayMember() &&
11419 "Incomplete array type is not valid");
11420 continue;
11421 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011422
11423 // Build references to the field in the object we're copying from and to.
11424 CXXScopeSpec SS; // Intentionally empty
11425 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11426 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011427 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011428 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011429
11430 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11431
11432 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011433
Douglas Gregorb139cd52010-05-01 20:49:11 +000011434 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011435 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011436 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011437 /*CopyingBaseSubobject=*/false,
11438 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011439 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011440 Diag(CurrentLocation, diag::note_member_synthesized_at)
11441 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11442 CopyAssignOperator->setInvalidDecl();
11443 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011444 }
11445
11446 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011447 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011448 }
11449
11450 if (!Invalid) {
11451 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011452 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011453
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011454 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011455 if (Return.isInvalid())
11456 Invalid = true;
11457 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011458 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011459
11460 if (Trap.hasErrorOccurred()) {
11461 Diag(CurrentLocation, diag::note_member_synthesized_at)
11462 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11463 Invalid = true;
11464 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011465 }
11466 }
11467
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011468 // The exception specification is needed because we are defining the
11469 // function.
11470 ResolveExceptionSpec(CurrentLocation,
11471 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11472
Douglas Gregorb139cd52010-05-01 20:49:11 +000011473 if (Invalid) {
11474 CopyAssignOperator->setInvalidDecl();
11475 return;
11476 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011477
11478 StmtResult Body;
11479 {
11480 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011481 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011482 /*isStmtExpr=*/false);
11483 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11484 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011485 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011486
11487 if (ASTMutationListener *L = getASTMutationListener()) {
11488 L->CompletedImplicitDefinition(CopyAssignOperator);
11489 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011490}
11491
Sebastian Redl22653ba2011-08-30 19:58:05 +000011492CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011493 assert(ClassDecl->needsImplicitMoveAssignment());
11494
Richard Smith8bf22e52012-11-29 01:34:07 +000011495 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11496 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011497 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011498
Sebastian Redl22653ba2011-08-30 19:58:05 +000011499 // Note: The following rules are largely analoguous to the move
11500 // constructor rules.
11501
Sebastian Redl22653ba2011-08-30 19:58:05 +000011502 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11503 QualType RetType = Context.getLValueReferenceType(ArgType);
11504 ArgType = Context.getRValueReferenceType(ArgType);
11505
Richard Smith99005e62013-05-07 03:19:20 +000011506 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11507 CXXMoveAssignment,
11508 false);
11509
Sebastian Redl22653ba2011-08-30 19:58:05 +000011510 // An implicitly-declared move assignment operator is an inline public
11511 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011512 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11513 SourceLocation ClassLoc = ClassDecl->getLocation();
11514 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011515 CXXMethodDecl *MoveAssignment =
11516 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011517 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011518 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011519 MoveAssignment->setAccess(AS_public);
11520 MoveAssignment->setDefaulted();
11521 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011522
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011523 if (getLangOpts().CUDA) {
11524 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11525 MoveAssignment,
11526 /* ConstRHS */ false,
11527 /* Diagnose */ false);
11528 }
11529
Richard Smithd3b5c9082012-07-27 04:22:15 +000011530 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011531 FunctionProtoType::ExtProtoInfo EPI =
11532 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011533 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011534
Sebastian Redl22653ba2011-08-30 19:58:05 +000011535 // Add the parameter to the operator.
11536 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011537 ClassLoc, ClassLoc,
11538 /*Id=*/nullptr, ArgType,
11539 /*TInfo=*/nullptr, SC_None,
11540 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011541 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011542
Richard Smith6b02d462012-12-08 08:32:28 +000011543 MoveAssignment->setTrivial(
11544 ClassDecl->needsOverloadResolutionForMoveAssignment()
11545 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11546 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011547
Richard Smith12e79312016-05-13 06:47:56 +000011548 // Note that we have added this copy-assignment operator.
11549 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11550
11551 Scope *S = getScopeForContext(ClassDecl);
11552 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11553
Richard Smithd951a1d2012-02-18 02:02:13 +000011554 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011555 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11556 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011557 }
11558
Richard Smith12e79312016-05-13 06:47:56 +000011559 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011560 PushOnScopeChains(MoveAssignment, S, false);
11561 ClassDecl->addDecl(MoveAssignment);
11562
Sebastian Redl22653ba2011-08-30 19:58:05 +000011563 return MoveAssignment;
11564}
11565
Richard Smithb2504bd2013-11-04 04:26:14 +000011566/// Check if we're implicitly defining a move assignment operator for a class
11567/// with virtual bases. Such a move assignment might move-assign the virtual
11568/// base multiple times.
11569static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11570 SourceLocation CurrentLocation) {
11571 assert(!Class->isDependentContext() && "should not define dependent move");
11572
11573 // Only a virtual base could get implicitly move-assigned multiple times.
11574 // Only a non-trivial move assignment can observe this. We only want to
11575 // diagnose if we implicitly define an assignment operator that assigns
11576 // two base classes, both of which move-assign the same virtual base.
11577 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11578 Class->getNumBases() < 2)
11579 return;
11580
11581 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11582 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11583 VBaseMap VBases;
11584
Aaron Ballman574705e2014-03-13 15:41:46 +000011585 for (auto &BI : Class->bases()) {
11586 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011587 while (!Worklist.empty()) {
11588 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11589 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11590
11591 // If the base has no non-trivial move assignment operators,
11592 // we don't care about moves from it.
11593 if (!Base->hasNonTrivialMoveAssignment())
11594 continue;
11595
11596 // If there's nothing virtual here, skip it.
11597 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11598 continue;
11599
11600 // If we're not actually going to call a move assignment for this base,
11601 // or the selected move assignment is trivial, skip it.
Richard Smith8bae1be2017-02-24 02:07:20 +000011602 Sema::SpecialMemberOverloadResult SMOR =
Richard Smithb2504bd2013-11-04 04:26:14 +000011603 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11604 /*ConstArg*/false, /*VolatileArg*/false,
11605 /*RValueThis*/true, /*ConstThis*/false,
11606 /*VolatileThis*/false);
Richard Smith8bae1be2017-02-24 02:07:20 +000011607 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11608 !SMOR.getMethod()->isMoveAssignmentOperator())
Richard Smithb2504bd2013-11-04 04:26:14 +000011609 continue;
11610
11611 if (BaseSpec->isVirtual()) {
11612 // We're going to move-assign this virtual base, and its move
11613 // assignment operator is not trivial. If this can happen for
11614 // multiple distinct direct bases of Class, diagnose it. (If it
11615 // only happens in one base, we'll diagnose it when synthesizing
11616 // that base class's move assignment operator.)
11617 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011618 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011619 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011620 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011621 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11622 << Class << Base;
11623 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11624 << (Base->getCanonicalDecl() ==
11625 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11626 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011627 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011628 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011629 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11630 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011631
11632 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011633 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011634 }
11635 } else {
11636 // Only walk over bases that have defaulted move assignment operators.
11637 // We assume that any user-provided move assignment operator handles
11638 // the multiple-moves-of-vbase case itself somehow.
Richard Smith8bae1be2017-02-24 02:07:20 +000011639 if (!SMOR.getMethod()->isDefaulted())
Richard Smithb2504bd2013-11-04 04:26:14 +000011640 continue;
11641
11642 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011643 for (auto &BI : Base->bases())
11644 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011645 }
11646 }
11647 }
11648}
11649
Sebastian Redl22653ba2011-08-30 19:58:05 +000011650void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11651 CXXMethodDecl *MoveAssignOperator) {
11652 assert((MoveAssignOperator->isDefaulted() &&
11653 MoveAssignOperator->isOverloadedOperator() &&
11654 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011655 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11656 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011657 "DefineImplicitMoveAssignment called for wrong function");
11658
11659 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11660
11661 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11662 MoveAssignOperator->setInvalidDecl();
11663 return;
11664 }
11665
Eli Friedman276dd182013-09-05 00:02:25 +000011666 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011667
Eli Friedmaneaf34142012-10-18 20:14:08 +000011668 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011669 DiagnosticErrorTrap Trap(Diags);
11670
11671 // C++0x [class.copy]p28:
11672 // The implicitly-defined or move assignment operator for a non-union class
11673 // X performs memberwise move assignment of its subobjects. The direct base
11674 // classes of X are assigned first, in the order of their declaration in the
11675 // base-specifier-list, and then the immediate non-static data members of X
11676 // are assigned, in the order in which they were declared in the class
11677 // definition.
11678
Richard Smithb2504bd2013-11-04 04:26:14 +000011679 // Issue a warning if our implicit move assignment operator will move
11680 // from a virtual base more than once.
11681 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011682
Sebastian Redl22653ba2011-08-30 19:58:05 +000011683 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011684 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011685
11686 // The parameter for the "other" object, which we are move from.
11687 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11688 QualType OtherRefType = Other->getType()->
11689 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011690 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011691 "Bad argument type of defaulted move assignment");
11692
11693 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011694 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11695 ? MoveAssignOperator->getLocEnd()
11696 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011697
Pavel Labath58934982013-08-30 08:52:28 +000011698 // Builds a reference to the "other" object.
11699 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011700 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011701 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011702
Pavel Labath58934982013-08-30 08:52:28 +000011703 // Builds the "this" pointer.
11704 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011705
Sebastian Redl22653ba2011-08-30 19:58:05 +000011706 // Assign base classes.
11707 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011708 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011709 // C++11 [class.copy]p28:
11710 // It is unspecified whether subobjects representing virtual base classes
11711 // are assigned more than once by the implicitly-defined copy assignment
11712 // operator.
11713 // FIXME: Do not assign to a vbase that will be assigned by some other base
11714 // class. For a move-assignment, this can result in the vbase being moved
11715 // multiple times.
11716
Sebastian Redl22653ba2011-08-30 19:58:05 +000011717 // Form the assignment:
11718 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011719 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011720 if (!BaseType->isRecordType()) {
11721 Invalid = true;
11722 continue;
11723 }
11724
11725 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011726 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011727
11728 // Construct the "from" expression, which is an implicit cast to the
11729 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011730 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011731
11732 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011733 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011734
11735 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011736 CastBuilder To(DerefThis,
11737 Context.getCVRQualifiedType(
11738 BaseType, MoveAssignOperator->getTypeQualifiers()),
11739 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011740
11741 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011742 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011743 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011744 /*CopyingBaseSubobject=*/true,
11745 /*Copying=*/false);
11746 if (Move.isInvalid()) {
11747 Diag(CurrentLocation, diag::note_member_synthesized_at)
11748 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11749 MoveAssignOperator->setInvalidDecl();
11750 return;
11751 }
11752
11753 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011754 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011755 }
11756
Sebastian Redl22653ba2011-08-30 19:58:05 +000011757 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011758 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011759 // FIXME: We should form some kind of AST representation for the implied
11760 // memcpy in a union copy operation.
11761 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011762 continue;
11763
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011764 if (Field->isInvalidDecl()) {
11765 Invalid = true;
11766 continue;
11767 }
11768
Sebastian Redl22653ba2011-08-30 19:58:05 +000011769 // Check for members of reference type; we can't move those.
11770 if (Field->getType()->isReferenceType()) {
11771 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11772 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11773 Diag(Field->getLocation(), diag::note_declared_at);
11774 Diag(CurrentLocation, diag::note_member_synthesized_at)
11775 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11776 Invalid = true;
11777 continue;
11778 }
11779
11780 // Check for members of const-qualified, non-class type.
11781 QualType BaseType = Context.getBaseElementType(Field->getType());
11782 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11783 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11784 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11785 Diag(Field->getLocation(), diag::note_declared_at);
11786 Diag(CurrentLocation, diag::note_member_synthesized_at)
11787 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11788 Invalid = true;
11789 continue;
11790 }
11791
11792 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011793 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11794 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011795
11796 QualType FieldType = Field->getType().getNonReferenceType();
11797 if (FieldType->isIncompleteArrayType()) {
11798 assert(ClassDecl->hasFlexibleArrayMember() &&
11799 "Incomplete array type is not valid");
11800 continue;
11801 }
11802
11803 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011804 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11805 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011806 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011807 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011808 MemberBuilder From(MoveOther, OtherRefType,
11809 /*IsArrow=*/false, MemberLookup);
11810 MemberBuilder To(This, getCurrentThisType(),
11811 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011812
Pavel Labath58934982013-08-30 08:52:28 +000011813 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011814 "Member reference with rvalue base must be rvalue except for reference "
11815 "members, which aren't allowed for move assignment.");
11816
Sebastian Redl22653ba2011-08-30 19:58:05 +000011817 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011818 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011819 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011820 /*CopyingBaseSubobject=*/false,
11821 /*Copying=*/false);
11822 if (Move.isInvalid()) {
11823 Diag(CurrentLocation, diag::note_member_synthesized_at)
11824 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11825 MoveAssignOperator->setInvalidDecl();
11826 return;
11827 }
Richard Smith11d19592012-11-12 23:33:00 +000011828
Sebastian Redl22653ba2011-08-30 19:58:05 +000011829 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011830 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011831 }
11832
11833 if (!Invalid) {
11834 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011835 ExprResult ThisObj =
11836 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11837
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011838 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011839 if (Return.isInvalid())
11840 Invalid = true;
11841 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011842 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011843
11844 if (Trap.hasErrorOccurred()) {
11845 Diag(CurrentLocation, diag::note_member_synthesized_at)
11846 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11847 Invalid = true;
11848 }
11849 }
11850 }
11851
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011852 // The exception specification is needed because we are defining the
11853 // function.
11854 ResolveExceptionSpec(CurrentLocation,
11855 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11856
Sebastian Redl22653ba2011-08-30 19:58:05 +000011857 if (Invalid) {
11858 MoveAssignOperator->setInvalidDecl();
11859 return;
11860 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011861
11862 StmtResult Body;
11863 {
11864 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011865 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011866 /*isStmtExpr=*/false);
11867 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11868 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011869 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011870
11871 if (ASTMutationListener *L = getASTMutationListener()) {
11872 L->CompletedImplicitDefinition(MoveAssignOperator);
11873 }
11874}
11875
Alexis Hunt913820d2011-05-13 06:10:58 +000011876CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11877 CXXRecordDecl *ClassDecl) {
11878 // C++ [class.copy]p4:
11879 // If the class definition does not explicitly declare a copy
11880 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011881 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011882
Richard Smith8bf22e52012-11-29 01:34:07 +000011883 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11884 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011885 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011886
Alexis Hunt913820d2011-05-13 06:10:58 +000011887 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11888 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011889 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011890 if (Const)
11891 ArgType = ArgType.withConst();
11892 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011893
Richard Smithb5800092012-06-10 05:43:50 +000011894 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11895 CXXCopyConstructor,
11896 Const);
11897
Douglas Gregor54be3392010-07-01 17:57:27 +000011898 DeclarationName Name
11899 = Context.DeclarationNames.getCXXConstructorName(
11900 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011901 SourceLocation ClassLoc = ClassDecl->getLocation();
11902 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011903
11904 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011905 // member of its class.
11906 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011907 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011908 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011909 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011910 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011911 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011912
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011913 if (getLangOpts().CUDA) {
11914 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11915 CopyConstructor,
11916 /* ConstRHS */ Const,
11917 /* Diagnose */ false);
11918 }
11919
Richard Smithd3b5c9082012-07-27 04:22:15 +000011920 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011921 FunctionProtoType::ExtProtoInfo EPI =
11922 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011923 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011924 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011925
Douglas Gregor54be3392010-07-01 17:57:27 +000011926 // Add the parameter to the constructor.
11927 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011928 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011929 /*IdentifierInfo=*/nullptr,
11930 ArgType, /*TInfo=*/nullptr,
11931 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011932 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011933
Richard Smith6b02d462012-12-08 08:32:28 +000011934 CopyConstructor->setTrivial(
11935 ClassDecl->needsOverloadResolutionForCopyConstructor()
11936 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11937 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011938
Richard Smith6b02d462012-12-08 08:32:28 +000011939 // Note that we have declared this constructor.
11940 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11941
Richard Smith12e79312016-05-13 06:47:56 +000011942 Scope *S = getScopeForContext(ClassDecl);
11943 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11944
11945 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11946 SetDeclDeleted(CopyConstructor, ClassLoc);
11947
11948 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011949 PushOnScopeChains(CopyConstructor, S, false);
11950 ClassDecl->addDecl(CopyConstructor);
11951
Douglas Gregor54be3392010-07-01 17:57:27 +000011952 return CopyConstructor;
11953}
11954
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011955void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011956 CXXConstructorDecl *CopyConstructor) {
11957 assert((CopyConstructor->isDefaulted() &&
11958 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011959 !CopyConstructor->doesThisDeclarationHaveABody() &&
11960 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011961 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011962
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011963 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011964 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011965
Richard Smithd577fbb2013-06-13 03:23:42 +000011966 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011967 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011968 // deprecated if the class has a user-declared copy assignment operator
11969 // or a user-declared destructor.
11970 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11971 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11972
Eli Friedmaneaf34142012-10-18 20:14:08 +000011973 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011974 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011975
David Blaikie3fc2f912013-01-17 05:26:25 +000011976 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011977 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011978 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011979 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011980 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011981 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011982 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11983 ? CopyConstructor->getLocEnd()
11984 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011985 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011986 CopyConstructor->setBody(
11987 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011988 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011989
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011990 // The exception specification is needed because we are defining the
11991 // function.
11992 ResolveExceptionSpec(CurrentLocation,
11993 CopyConstructor->getType()->castAs<FunctionProtoType>());
11994
Eli Friedman276dd182013-09-05 00:02:25 +000011995 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011996 MarkVTableUsed(CurrentLocation, ClassDecl);
11997
Sebastian Redlab238a72011-04-24 16:28:06 +000011998 if (ASTMutationListener *L = getASTMutationListener()) {
11999 L->CompletedImplicitDefinition(CopyConstructor);
12000 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012001}
12002
Sebastian Redl22653ba2011-08-30 19:58:05 +000012003CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12004 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000012005 assert(ClassDecl->needsImplicitMoveConstructor());
12006
Richard Smith8bf22e52012-11-29 01:34:07 +000012007 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12008 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000012009 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000012010
Sebastian Redl22653ba2011-08-30 19:58:05 +000012011 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12012 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012013
Richard Smithb5800092012-06-10 05:43:50 +000012014 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12015 CXXMoveConstructor,
12016 false);
12017
Sebastian Redl22653ba2011-08-30 19:58:05 +000012018 DeclarationName Name
12019 = Context.DeclarationNames.getCXXConstructorName(
12020 Context.getCanonicalType(ClassType));
12021 SourceLocation ClassLoc = ClassDecl->getLocation();
12022 DeclarationNameInfo NameInfo(Name, ClassLoc);
12023
Richard Smith99005e62013-05-07 03:19:20 +000012024 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000012025 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000012026 // member of its class.
12027 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000012028 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000012029 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000012030 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012031 MoveConstructor->setAccess(AS_public);
12032 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000012033
Eli Bendersky9a220fc2014-09-29 20:38:29 +000012034 if (getLangOpts().CUDA) {
12035 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12036 MoveConstructor,
12037 /* ConstRHS */ false,
12038 /* Diagnose */ false);
12039 }
12040
Richard Smithd3b5c9082012-07-27 04:22:15 +000012041 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000012042 FunctionProtoType::ExtProtoInfo EPI =
12043 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012044 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012045 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012046
Sebastian Redl22653ba2011-08-30 19:58:05 +000012047 // Add the parameter to the constructor.
12048 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12049 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012050 /*IdentifierInfo=*/nullptr,
12051 ArgType, /*TInfo=*/nullptr,
12052 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012053 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012054
Richard Smith6b02d462012-12-08 08:32:28 +000012055 MoveConstructor->setTrivial(
12056 ClassDecl->needsOverloadResolutionForMoveConstructor()
12057 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12058 : ClassDecl->hasTrivialMoveConstructor());
12059
Richard Smith12e79312016-05-13 06:47:56 +000012060 // Note that we have declared this constructor.
12061 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12062
12063 Scope *S = getScopeForContext(ClassDecl);
12064 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12065
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012066 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012067 ClassDecl->setImplicitMoveConstructorIsDeleted();
12068 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012069 }
12070
Richard Smith12e79312016-05-13 06:47:56 +000012071 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012072 PushOnScopeChains(MoveConstructor, S, false);
12073 ClassDecl->addDecl(MoveConstructor);
12074
12075 return MoveConstructor;
12076}
12077
12078void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12079 CXXConstructorDecl *MoveConstructor) {
12080 assert((MoveConstructor->isDefaulted() &&
12081 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012082 !MoveConstructor->doesThisDeclarationHaveABody() &&
12083 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012084 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12085
12086 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12087 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12088
Eli Friedmaneaf34142012-10-18 20:14:08 +000012089 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012090 DiagnosticErrorTrap Trap(Diags);
12091
David Blaikie3fc2f912013-01-17 05:26:25 +000012092 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012093 Trap.hasErrorOccurred()) {
12094 Diag(CurrentLocation, diag::note_member_synthesized_at)
12095 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12096 MoveConstructor->setInvalidDecl();
12097 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012098 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12099 ? MoveConstructor->getLocEnd()
12100 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012101 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012102 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012103 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012104 }
12105
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012106 // The exception specification is needed because we are defining the
12107 // function.
12108 ResolveExceptionSpec(CurrentLocation,
12109 MoveConstructor->getType()->castAs<FunctionProtoType>());
12110
Eli Friedman276dd182013-09-05 00:02:25 +000012111 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012112 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012113
12114 if (ASTMutationListener *L = getASTMutationListener()) {
12115 L->CompletedImplicitDefinition(MoveConstructor);
12116 }
12117}
12118
Douglas Gregor74f7d502012-02-15 19:33:52 +000012119bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012120 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012121}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012122
12123void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012124 SourceLocation CurrentLocation,
12125 CXXConversionDecl *Conv) {
12126 CXXRecordDecl *Lambda = Conv->getParent();
12127 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12128 // If we are defining a specialization of a conversion to function-ptr
12129 // cache the deduced template arguments for this specialization
12130 // so that we can use them to retrieve the corresponding call-operator
12131 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12133
Faisal Vali571df122013-09-29 08:45:24 +000012134 // Retrieve the corresponding call-operator specialization.
12135 if (Lambda->isGenericLambda()) {
12136 assert(Conv->isFunctionTemplateSpecialization());
12137 FunctionTemplateDecl *CallOpTemplate =
12138 CallOp->getDescribedFunctionTemplate();
12139 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012140 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012141 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012142 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012143 InsertPos);
12144 assert(CallOpSpec &&
12145 "Conversion operator must have a corresponding call operator");
12146 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12147 }
12148 // Mark the call operator referenced (and add to pending instantiations
12149 // if necessary).
12150 // For both the conversion and static-invoker template specializations
12151 // we construct their body's in this function, so no need to add them
12152 // to the PendingInstantiations.
12153 MarkFunctionReferenced(CurrentLocation, CallOp);
12154
Eli Friedmaneaf34142012-10-18 20:14:08 +000012155 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012156 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012157
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012158 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012159 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12160 // ... and get the corresponding specialization for a generic lambda.
12161 if (Lambda->isGenericLambda()) {
12162 assert(DeducedTemplateArgs &&
12163 "Must have deduced template arguments from Conversion Operator");
12164 FunctionTemplateDecl *InvokeTemplate =
12165 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012166 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012167 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012168 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012169 InsertPos);
12170 assert(InvokeSpec &&
12171 "Must have a corresponding static invoker specialization");
12172 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12173 }
12174 // Construct the body of the conversion function { return __invoke; }.
12175 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012176 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012177 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012178 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012179 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12180 Conv->getLocation(),
12181 Conv->getLocation()));
12182
12183 Conv->markUsed(Context);
12184 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012185
Faisal Vali571df122013-09-29 08:45:24 +000012186 // Fill in the __invoke function with a dummy implementation. IR generation
12187 // will fill in the actual details.
12188 Invoker->markUsed(Context);
12189 Invoker->setReferenced();
12190 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12191
Douglas Gregord3b672c2012-02-16 01:06:16 +000012192 if (ASTMutationListener *L = getASTMutationListener()) {
12193 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012194 L->CompletedImplicitDefinition(Invoker);
12195 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012196}
12197
Faisal Vali571df122013-09-29 08:45:24 +000012198
12199
Douglas Gregord3b672c2012-02-16 01:06:16 +000012200void Sema::DefineImplicitLambdaToBlockPointerConversion(
12201 SourceLocation CurrentLocation,
12202 CXXConversionDecl *Conv)
12203{
Faisal Vali850da1a2013-09-29 17:08:32 +000012204 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012205
Eli Friedman276dd182013-09-05 00:02:25 +000012206 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012207
Eli Friedmaneaf34142012-10-18 20:14:08 +000012208 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012209 DiagnosticErrorTrap Trap(Diags);
12210
Douglas Gregored90df32012-02-22 05:02:47 +000012211 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012212 Expr *This = ActOnCXXThis(CurrentLocation).get();
12213 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012214
Eli Friedman98b01ed2012-03-01 04:01:32 +000012215 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12216 Conv->getLocation(),
12217 Conv, DerefThis);
12218
12219 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12220 // behavior. Note that only the general conversion function does this
12221 // (since it's unusable otherwise); in the case where we inline the
12222 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012223 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012224 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12225 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012226 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012227
12228 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012229 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012230 Conv->setInvalidDecl();
12231 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012232 }
Douglas Gregored90df32012-02-22 05:02:47 +000012233
Douglas Gregored90df32012-02-22 05:02:47 +000012234 // Create the return statement that returns the block from the conversion
12235 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012236 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012237 if (Return.isInvalid()) {
12238 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12239 Conv->setInvalidDecl();
12240 return;
12241 }
12242
12243 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012244 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012245 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012246 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012247 Conv->getLocation()));
12248
Douglas Gregored90df32012-02-22 05:02:47 +000012249 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012250 if (ASTMutationListener *L = getASTMutationListener()) {
12251 L->CompletedImplicitDefinition(Conv);
12252 }
12253}
12254
Douglas Gregord2f70072012-03-10 06:53:13 +000012255/// \brief Determine whether the given list arguments contains exactly one
12256/// "real" (non-default) argument.
12257static bool hasOneRealArgument(MultiExprArg Args) {
12258 switch (Args.size()) {
12259 case 0:
12260 return false;
12261
12262 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012263 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012264 return false;
12265
12266 // fall through
12267 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012268 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012269 }
12270
12271 return false;
12272}
12273
John McCalldadc5752010-08-24 06:29:42 +000012274ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012275Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012276 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012277 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012278 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012279 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012280 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012281 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012282 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012283 unsigned ConstructKind,
12284 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012285 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012286
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012287 // C++0x [class.copy]p34:
12288 // When certain criteria are met, an implementation is allowed to
12289 // omit the copy/move construction of a class object, even if the
12290 // copy/move constructor and/or destructor for the object have
12291 // side effects. [...]
12292 // - when a temporary class object that has not been bound to a
12293 // reference (12.2) would be copied/moved to a class object
12294 // with the same cv-unqualified type, the copy/move operation
12295 // can be omitted by constructing the temporary object
12296 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012297 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012298 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012299 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012300 Elidable = SubExpr->isTemporaryObject(
12301 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012302 }
Mike Stump11289f42009-09-09 15:08:12 +000012303
Richard Smithc2bebe92016-05-11 20:37:46 +000012304 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12305 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012306 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012307 IsListInitialization,
12308 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012309 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012310}
12311
John McCalldadc5752010-08-24 06:29:42 +000012312ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012313Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012314 NamedDecl *FoundDecl,
12315 CXXConstructorDecl *Constructor,
12316 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012317 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012318 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012319 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012320 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012321 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012322 unsigned ConstructKind,
12323 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012324 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012325 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012326 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12327 return ExprError();
12328 }
Richard Smith5179eb72016-06-28 19:03:57 +000012329
Richard Smithc83bf822016-06-10 00:58:19 +000012330 return BuildCXXConstructExpr(
12331 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12332 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12333 RequiresZeroInit, ConstructKind, ParenRange);
12334}
12335
12336/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12337/// including handling of its default argument expressions.
12338ExprResult
12339Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12340 CXXConstructorDecl *Constructor,
12341 bool Elidable,
12342 MultiExprArg ExprArgs,
12343 bool HadMultipleCandidates,
12344 bool IsListInitialization,
12345 bool IsStdInitListInitialization,
12346 bool RequiresZeroInit,
12347 unsigned ConstructKind,
12348 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012349 assert(declaresSameEntity(
12350 Constructor->getParent(),
12351 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12352 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012353 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012354 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12355 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012356
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012357 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012358 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012359 ExprArgs, HadMultipleCandidates, IsListInitialization,
12360 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012361 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12362 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012363}
12364
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012365ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12366 assert(Field->hasInClassInitializer());
12367
12368 // If we already have the in-class initializer nothing needs to be done.
12369 if (Field->getInClassInitializer())
12370 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12371
Richard Smithd6a15082017-01-07 00:48:55 +000012372 // If we might have already tried and failed to instantiate, don't try again.
12373 if (Field->isInvalidDecl())
12374 return ExprError();
12375
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012376 // Maybe we haven't instantiated the in-class initializer. Go check the
12377 // pattern FieldDecl to see if it has one.
12378 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12379
12380 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12381 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12382 DeclContext::lookup_result Lookup =
12383 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012384
12385 // Lookup can return at most two results: the pattern for the field, or the
12386 // injected class name of the parent record. No other member can have the
12387 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012388 // In modules mode, lookup can return multiple results (coming from
12389 // different modules).
12390 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012391 "more than two lookup results for field name");
12392 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12393 if (!Pattern) {
12394 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12395 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012396 for (auto L : Lookup)
12397 if (isa<FieldDecl>(L)) {
12398 Pattern = cast<FieldDecl>(L);
12399 break;
12400 }
12401 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012402 }
12403
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012404 if (InstantiateInClassInitializer(Loc, Field, Pattern,
Richard Smithd6a15082017-01-07 00:48:55 +000012405 getTemplateInstantiationArgs(Field))) {
12406 // Don't diagnose this again.
12407 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012408 return ExprError();
Richard Smithd6a15082017-01-07 00:48:55 +000012409 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012410 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12411 }
12412
12413 // DR1351:
12414 // If the brace-or-equal-initializer of a non-static data member
12415 // invokes a defaulted default constructor of its class or of an
12416 // enclosing class in a potentially evaluated subexpression, the
12417 // program is ill-formed.
12418 //
12419 // This resolution is unworkable: the exception specification of the
12420 // default constructor can be needed in an unevaluated context, in
12421 // particular, in the operand of a noexcept-expression, and we can be
12422 // unable to compute an exception specification for an enclosed class.
12423 //
12424 // Any attempt to resolve the exception specification of a defaulted default
12425 // constructor before the initializer is lexically complete will ultimately
12426 // come here at which point we can diagnose it.
12427 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012428 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12429 << OutermostClass << Field;
12430 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Richard Smith8d148352017-01-23 23:14:23 +000012431 // Recover by marking the field invalid, unless we're in a SFINAE context.
12432 if (!isSFINAEContext())
12433 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012434 return ExprError();
12435}
12436
John McCall03c48482010-02-02 09:10:11 +000012437void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012438 if (VD->isInvalidDecl()) return;
12439
John McCall03c48482010-02-02 09:10:11 +000012440 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012441 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012442 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012443 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012444
Chandler Carruth86d17d32011-03-27 21:26:48 +000012445 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012446 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012447 CheckDestructorAccess(VD->getLocation(), Destructor,
12448 PDiag(diag::err_access_dtor_var)
12449 << VD->getDeclName()
12450 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012451 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012452
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012453 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012454 if (!VD->hasGlobalStorage()) return;
12455
12456 // Emit warning for non-trivial dtor in global scope (a real global,
12457 // class-static, function-static).
12458 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12459
12460 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012461 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012462 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012463}
12464
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012465/// \brief Given a constructor and the set of arguments provided for the
12466/// constructor, convert the arguments and add any required default arguments
12467/// to form a proper call to this constructor.
12468///
12469/// \returns true if an error occurred, false otherwise.
12470bool
12471Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12472 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012473 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012474 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012475 bool AllowExplicit,
12476 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012477 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12478 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012479 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012480
12481 const FunctionProtoType *Proto
12482 = Constructor->getType()->getAs<FunctionProtoType>();
12483 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012484 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012485
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012486 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012487 if (NumArgs < NumParams)
12488 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012489 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012490 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012491
12492 VariadicCallType CallType =
12493 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012494 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012495 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012496 Proto, 0,
12497 llvm::makeArrayRef(Args, NumArgs),
12498 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012499 CallType, AllowExplicit,
12500 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012501 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012502
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012503 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012504
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012505 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012506 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012507 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012508
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012509 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012510}
12511
Anders Carlssone363c8e2009-12-12 00:32:00 +000012512static inline bool
12513CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12514 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012515 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012516 if (isa<NamespaceDecl>(DC)) {
12517 return SemaRef.Diag(FnDecl->getLocation(),
12518 diag::err_operator_new_delete_declared_in_namespace)
12519 << FnDecl->getDeclName();
12520 }
12521
12522 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012523 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012524 return SemaRef.Diag(FnDecl->getLocation(),
12525 diag::err_operator_new_delete_declared_static)
12526 << FnDecl->getDeclName();
12527 }
12528
Anders Carlsson60659a82009-12-12 02:43:16 +000012529 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012530}
12531
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012532static inline bool
12533CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12534 CanQualType ExpectedResultType,
12535 CanQualType ExpectedFirstParamType,
12536 unsigned DependentParamTypeDiag,
12537 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012538 QualType ResultType =
12539 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012540
12541 // Check that the result type is not dependent.
12542 if (ResultType->isDependentType())
12543 return SemaRef.Diag(FnDecl->getLocation(),
12544 diag::err_operator_new_delete_dependent_result_type)
12545 << FnDecl->getDeclName() << ExpectedResultType;
12546
12547 // Check that the result type is what we expect.
12548 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12549 return SemaRef.Diag(FnDecl->getLocation(),
12550 diag::err_operator_new_delete_invalid_result_type)
12551 << FnDecl->getDeclName() << ExpectedResultType;
12552
12553 // A function template must have at least 2 parameters.
12554 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12555 return SemaRef.Diag(FnDecl->getLocation(),
12556 diag::err_operator_new_delete_template_too_few_parameters)
12557 << FnDecl->getDeclName();
12558
12559 // The function decl must have at least 1 parameter.
12560 if (FnDecl->getNumParams() == 0)
12561 return SemaRef.Diag(FnDecl->getLocation(),
12562 diag::err_operator_new_delete_too_few_parameters)
12563 << FnDecl->getDeclName();
12564
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012565 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012566 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12567 if (FirstParamType->isDependentType())
12568 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12569 << FnDecl->getDeclName() << ExpectedFirstParamType;
12570
12571 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012572 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012573 ExpectedFirstParamType)
12574 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12575 << FnDecl->getDeclName() << ExpectedFirstParamType;
12576
12577 return false;
12578}
12579
Anders Carlsson12308f42009-12-11 23:23:22 +000012580static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012581CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012582 // C++ [basic.stc.dynamic.allocation]p1:
12583 // A program is ill-formed if an allocation function is declared in a
12584 // namespace scope other than global scope or declared static in global
12585 // scope.
12586 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12587 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012588
12589 CanQualType SizeTy =
12590 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12591
12592 // C++ [basic.stc.dynamic.allocation]p1:
12593 // The return type shall be void*. The first parameter shall have type
12594 // std::size_t.
12595 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12596 SizeTy,
12597 diag::err_operator_new_dependent_param_type,
12598 diag::err_operator_new_param_type))
12599 return true;
12600
12601 // C++ [basic.stc.dynamic.allocation]p1:
12602 // The first parameter shall not have an associated default argument.
12603 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012604 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012605 diag::err_operator_new_default_arg)
12606 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12607
12608 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012609}
12610
12611static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012612CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012613 // C++ [basic.stc.dynamic.deallocation]p1:
12614 // A program is ill-formed if deallocation functions are declared in a
12615 // namespace scope other than global scope or declared static in global
12616 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012617 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12618 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012619
12620 // C++ [basic.stc.dynamic.deallocation]p2:
12621 // Each deallocation function shall return void and its first parameter
12622 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012623 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12624 SemaRef.Context.VoidPtrTy,
12625 diag::err_operator_delete_dependent_param_type,
12626 diag::err_operator_delete_param_type))
12627 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012628
Anders Carlsson12308f42009-12-11 23:23:22 +000012629 return false;
12630}
12631
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012632/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12633/// of this overloaded operator is well-formed. If so, returns false;
12634/// otherwise, emits appropriate diagnostics and returns true.
12635bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012636 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012637 "Expected an overloaded operator declaration");
12638
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012639 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12640
Mike Stump11289f42009-09-09 15:08:12 +000012641 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012642 // The allocation and deallocation functions, operator new,
12643 // operator new[], operator delete and operator delete[], are
12644 // described completely in 3.7.3. The attributes and restrictions
12645 // found in the rest of this subclause do not apply to them unless
12646 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012647 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012648 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012649
Anders Carlsson22f443f2009-12-12 00:26:23 +000012650 if (Op == OO_New || Op == OO_Array_New)
12651 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012652
12653 // C++ [over.oper]p6:
12654 // An operator function shall either be a non-static member
12655 // function or be a non-member function and have at least one
12656 // parameter whose type is a class, a reference to a class, an
12657 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012658 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12659 if (MethodDecl->isStatic())
12660 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012661 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012662 } else {
12663 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012664 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012665 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012666 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12667 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012668 ClassOrEnumParam = true;
12669 break;
12670 }
12671 }
12672
Douglas Gregord69246b2008-11-17 16:14:12 +000012673 if (!ClassOrEnumParam)
12674 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012675 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012676 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012677 }
12678
12679 // C++ [over.oper]p8:
12680 // An operator function cannot have default arguments (8.3.6),
12681 // except where explicitly stated below.
12682 //
Mike Stump11289f42009-09-09 15:08:12 +000012683 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012684 // (C++ [over.call]p1).
12685 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012686 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012687 if (Param->hasDefaultArg())
12688 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012689 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012690 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012691 }
12692 }
12693
Douglas Gregor6cf08062008-11-10 13:38:07 +000012694 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12695 { false, false, false }
12696#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12697 , { Unary, Binary, MemberOnly }
12698#include "clang/Basic/OperatorKinds.def"
12699 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012700
Douglas Gregor6cf08062008-11-10 13:38:07 +000012701 bool CanBeUnaryOperator = OperatorUses[Op][0];
12702 bool CanBeBinaryOperator = OperatorUses[Op][1];
12703 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012704
12705 // C++ [over.oper]p8:
12706 // [...] Operator functions cannot have more or fewer parameters
12707 // than the number required for the corresponding operator, as
12708 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012709 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012710 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012711 if (Op != OO_Call &&
12712 ((NumParams == 1 && !CanBeUnaryOperator) ||
12713 (NumParams == 2 && !CanBeBinaryOperator) ||
12714 (NumParams < 1) || (NumParams > 2))) {
12715 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012716 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012717 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012718 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012719 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012720 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012721 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012722 assert(CanBeBinaryOperator &&
12723 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012724 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012725 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012726
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012727 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012728 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012729 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012730
Douglas Gregord69246b2008-11-17 16:14:12 +000012731 // Overloaded operators other than operator() cannot be variadic.
12732 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012733 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012734 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012735 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012736 }
12737
12738 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012739 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12740 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012741 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012742 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012743 }
12744
12745 // C++ [over.inc]p1:
12746 // The user-defined function called operator++ implements the
12747 // prefix and postfix ++ operator. If this function is a member
12748 // function with no parameters, or a non-member function with one
12749 // parameter of class or enumeration type, it defines the prefix
12750 // increment operator ++ for objects of that type. If the function
12751 // is a member function with one parameter (which shall be of type
12752 // int) or a non-member function with two parameters (the second
12753 // of which shall be of type int), it defines the postfix
12754 // increment operator ++ for objects of that type.
12755 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12756 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012757 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012758
Richard Smith538b52a2014-01-30 22:24:05 +000012759 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12760 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012761 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012762 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012763 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012764 }
12765
Douglas Gregord69246b2008-11-17 16:14:12 +000012766 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012767}
Chris Lattner3b024a32008-12-17 07:09:26 +000012768
Richard Smithc28aee62016-02-17 00:04:04 +000012769static bool
12770checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12771 FunctionTemplateDecl *TpDecl) {
12772 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12773
12774 // Must have one or two template parameters.
12775 if (TemplateParams->size() == 1) {
12776 NonTypeTemplateParmDecl *PmDecl =
12777 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12778
12779 // The template parameter must be a char parameter pack.
12780 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12781 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12782 return false;
12783
12784 } else if (TemplateParams->size() == 2) {
12785 TemplateTypeParmDecl *PmType =
12786 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12787 NonTypeTemplateParmDecl *PmArgs =
12788 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12789
12790 // The second template parameter must be a parameter pack with the
12791 // first template parameter as its type.
12792 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12793 PmArgs->isTemplateParameterPack()) {
12794 const TemplateTypeParmType *TArgs =
12795 PmArgs->getType()->getAs<TemplateTypeParmType>();
12796 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12797 TArgs->getIndex() == PmType->getIndex()) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000012798 if (!SemaRef.inTemplateInstantiation())
Richard Smithc28aee62016-02-17 00:04:04 +000012799 SemaRef.Diag(TpDecl->getLocation(),
12800 diag::ext_string_literal_operator_template);
12801 return false;
12802 }
12803 }
12804 }
12805
12806 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12807 diag::err_literal_operator_template)
12808 << TpDecl->getTemplateParameters()->getSourceRange();
12809 return true;
12810}
12811
Alexis Huntc88db062010-01-13 09:01:02 +000012812/// CheckLiteralOperatorDeclaration - Check whether the declaration
12813/// of this literal operator function is well-formed. If so, returns
12814/// false; otherwise, emits appropriate diagnostics and returns true.
12815bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012816 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012817 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12818 << FnDecl->getDeclName();
12819 return true;
12820 }
12821
Richard Smith72eebee2012-03-04 09:41:16 +000012822 if (FnDecl->isExternC()) {
12823 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012824 if (const LinkageSpecDecl *LSD =
12825 FnDecl->getDeclContext()->getExternCContext())
12826 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012827 return true;
12828 }
12829
Richard Smithbcc22fc2012-03-09 08:00:36 +000012830 // This might be the definition of a literal operator template.
12831 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012832
Richard Smithbcc22fc2012-03-09 08:00:36 +000012833 // This might be a specialization of a literal operator template.
12834 if (!TpDecl)
12835 TpDecl = FnDecl->getPrimaryTemplate();
12836
Richard Smithb8b41d32013-10-07 19:57:58 +000012837 // template <char...> type operator "" name() and
12838 // template <class T, T...> type operator "" name() are the only valid
12839 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012840 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012841 if (FnDecl->param_size() != 0) {
12842 Diag(FnDecl->getLocation(),
12843 diag::err_literal_operator_template_with_params);
12844 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012845 }
Richard Smithc28aee62016-02-17 00:04:04 +000012846
12847 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12848 return true;
12849
12850 } else if (FnDecl->param_size() == 1) {
12851 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12852
12853 QualType ParamType = Param->getType().getUnqualifiedType();
12854
12855 // Only unsigned long long int, long double, any character type, and const
12856 // char * are allowed as the only parameters.
12857 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12858 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12859 Context.hasSameType(ParamType, Context.CharTy) ||
12860 Context.hasSameType(ParamType, Context.WideCharTy) ||
12861 Context.hasSameType(ParamType, Context.Char16Ty) ||
12862 Context.hasSameType(ParamType, Context.Char32Ty)) {
12863 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12864 QualType InnerType = Ptr->getPointeeType();
12865
12866 // Pointer parameter must be a const char *.
12867 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12868 Context.CharTy) &&
12869 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12870 Diag(Param->getSourceRange().getBegin(),
12871 diag::err_literal_operator_param)
12872 << ParamType << "'const char *'" << Param->getSourceRange();
12873 return true;
12874 }
12875
12876 } else if (ParamType->isRealFloatingType()) {
12877 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12878 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12879 return true;
12880
12881 } else if (ParamType->isIntegerType()) {
12882 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12883 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12884 return true;
12885
12886 } else {
12887 Diag(Param->getSourceRange().getBegin(),
12888 diag::err_literal_operator_invalid_param)
12889 << ParamType << Param->getSourceRange();
12890 return true;
12891 }
12892
12893 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012894 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12895
Richard Smithc28aee62016-02-17 00:04:04 +000012896 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012897
Richard Smithc28aee62016-02-17 00:04:04 +000012898 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12899
12900 // Two parameter function must have a pointer to const as a
12901 // first parameter; let's strip those qualifiers.
12902 const PointerType *PT = FirstParamType->getAs<PointerType>();
12903
12904 if (!PT) {
12905 Diag((*Param)->getSourceRange().getBegin(),
12906 diag::err_literal_operator_param)
12907 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12908 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012909 }
12910
Richard Smithc28aee62016-02-17 00:04:04 +000012911 QualType PointeeType = PT->getPointeeType();
12912 // First parameter must be const
12913 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12914 Diag((*Param)->getSourceRange().getBegin(),
12915 diag::err_literal_operator_param)
12916 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12917 return true;
12918 }
Alexis Huntc88db062010-01-13 09:01:02 +000012919
Richard Smithc28aee62016-02-17 00:04:04 +000012920 QualType InnerType = PointeeType.getUnqualifiedType();
12921 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12922 // are allowed as the first parameter to a two-parameter function
12923 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12924 Context.hasSameType(InnerType, Context.WideCharTy) ||
12925 Context.hasSameType(InnerType, Context.Char16Ty) ||
12926 Context.hasSameType(InnerType, Context.Char32Ty))) {
12927 Diag((*Param)->getSourceRange().getBegin(),
12928 diag::err_literal_operator_param)
12929 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12930 return true;
12931 }
12932
12933 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012934 ++Param;
12935
Richard Smithc28aee62016-02-17 00:04:04 +000012936 // The second parameter must be a std::size_t.
12937 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12938 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12939 Diag((*Param)->getSourceRange().getBegin(),
12940 diag::err_literal_operator_param)
12941 << SecondParamType << Context.getSizeType()
12942 << (*Param)->getSourceRange();
12943 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012944 }
Richard Smithc28aee62016-02-17 00:04:04 +000012945 } else {
12946 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012947 return true;
12948 }
12949
Richard Smithc28aee62016-02-17 00:04:04 +000012950 // Parameters are good.
12951
Richard Smith768cecc2012-03-09 08:16:22 +000012952 // A parameter-declaration-clause containing a default argument is not
12953 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012954 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012955 if (Param->hasDefaultArg()) {
12956 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012957 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012958 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012959 break;
12960 }
12961 }
12962
Richard Smith0df56f42012-03-08 02:39:21 +000012963 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012964 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12965 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012966 // C++11 [usrlit.suffix]p1:
12967 // Literal suffix identifiers that do not start with an underscore
12968 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012969 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
Eric Fiseliercb2f3262016-12-30 04:51:10 +000012970 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012971 }
Richard Smith0df56f42012-03-08 02:39:21 +000012972
Alexis Huntc88db062010-01-13 09:01:02 +000012973 return false;
12974}
12975
Douglas Gregor07665a62009-01-05 19:45:36 +000012976/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12977/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012978/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12979/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012980/// the '{' brace. Otherwise, this linkage specification does not
12981/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012982Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012983 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012984 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012985 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12986 if (!Lit->isAscii()) {
12987 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12988 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012989 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012990 }
12991
12992 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012993 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012994 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012995 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012996 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012997 Language = LinkageSpecDecl::lang_cxx;
12998 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012999 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13000 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013001 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000013002 }
Mike Stump11289f42009-09-09 15:08:12 +000013003
Chris Lattner438e5012008-12-17 07:13:27 +000013004 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000013005
Richard Smith4ee696d2014-02-17 23:25:27 +000013006 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13007 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000013008 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013009 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000013010 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000013011 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000013012}
13013
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000013014/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000013015/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13016/// valid, it's the position of the closing '}' brace in a linkage
13017/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000013018Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013019 Decl *LinkageSpec,
13020 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013021 if (RBraceLoc.isValid()) {
13022 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13023 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013024 }
Richard Smith4ee696d2014-02-17 23:25:27 +000013025 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000013026 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000013027}
13028
Michael Han84324352013-02-22 17:15:32 +000013029Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13030 AttributeList *AttrList,
13031 SourceLocation SemiLoc) {
13032 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13033 // Attribute declarations appertain to empty declaration so we handle
13034 // them here.
13035 if (AttrList)
13036 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000013037
Michael Han84324352013-02-22 17:15:32 +000013038 CurContext->addDecl(ED);
13039 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000013040}
13041
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013042/// \brief Perform semantic analysis for the variable declaration that
13043/// occurs within a C++ catch clause, returning the newly-created
13044/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000013045VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000013046 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000013047 SourceLocation StartLoc,
13048 SourceLocation Loc,
13049 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013050 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013051 QualType ExDeclType = TInfo->getType();
13052
Sebastian Redl54c04d42008-12-22 19:15:10 +000013053 // Arrays and functions decay.
13054 if (ExDeclType->isArrayType())
13055 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13056 else if (ExDeclType->isFunctionType())
13057 ExDeclType = Context.getPointerType(ExDeclType);
13058
13059 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13060 // The exception-declaration shall not denote a pointer or reference to an
13061 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013062 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013063 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013064 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013065 Invalid = true;
13066 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013067
David Majnemere56d1a02016-06-08 16:05:07 +000013068 if (ExDeclType->isVariablyModifiedType()) {
13069 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13070 Invalid = true;
13071 }
13072
Sebastian Redl54c04d42008-12-22 19:15:10 +000013073 QualType BaseType = ExDeclType;
13074 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013075 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013076 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013077 BaseType = Ptr->getPointeeType();
13078 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013079 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013080 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013081 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013082 BaseType = Ref->getPointeeType();
13083 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013084 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013085 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013086 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013087 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013088 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013089
Mike Stump11289f42009-09-09 15:08:12 +000013090 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013091 RequireNonAbstractType(Loc, ExDeclType,
13092 diag::err_abstract_type_in_decl,
13093 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013094 Invalid = true;
13095
John McCall2ca705e2010-07-24 00:37:23 +000013096 // Only the non-fragile NeXT runtime currently supports C++ catches
13097 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013098 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013099 QualType T = ExDeclType;
13100 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13101 T = RT->getPointeeType();
13102
13103 if (T->isObjCObjectType()) {
13104 Diag(Loc, diag::err_objc_object_catch);
13105 Invalid = true;
13106 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013107 // FIXME: should this be a test for macosx-fragile specifically?
13108 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013109 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013110 }
13111 }
13112
Abramo Bagnaradff19302011-03-08 08:55:46 +000013113 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013114 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013115 ExDecl->setExceptionVariable(true);
13116
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013117 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013118 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013119 Invalid = true;
13120
Douglas Gregor750734c2011-07-06 18:14:43 +000013121 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013122 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013123 // Insulate this from anything else we might currently be parsing.
13124 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13125
Douglas Gregor6de584c2010-03-05 23:38:39 +000013126 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013127 // The object declared in an exception-declaration or, if the
13128 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013129 // copy-initialized (8.5) from the exception object. [...]
13130 // The object is destroyed when the handler exits, after the destruction
13131 // of any automatic objects initialized within the handler.
13132 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013133 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013134 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013135 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013136
13137 InitializedEntity entity =
13138 InitializedEntity::InitializeVariable(ExDecl);
13139 InitializationKind initKind =
13140 InitializationKind::CreateCopy(Loc, SourceLocation());
13141
13142 Expr *opaqueValue =
13143 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013144 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13145 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013146 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013147 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013148 else {
13149 // If the constructor used was non-trivial, set this as the
13150 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013151 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013152 if (!construct->getConstructor()->isTrivial()) {
13153 Expr *init = MaybeCreateExprWithCleanups(construct);
13154 ExDecl->setInit(init);
13155 }
13156
13157 // And make sure it's destructable.
13158 FinalizeVarWithDestructor(ExDecl, recordType);
13159 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013160 }
13161 }
13162
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013163 if (Invalid)
13164 ExDecl->setInvalidDecl();
13165
13166 return ExDecl;
13167}
13168
13169/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13170/// handler.
John McCall48871652010-08-21 09:40:31 +000013171Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013172 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013173 bool Invalid = D.isInvalidType();
13174
13175 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013176 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13177 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013178 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13179 D.getIdentifierLoc());
13180 Invalid = true;
13181 }
13182
Sebastian Redl54c04d42008-12-22 19:15:10 +000013183 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013184 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013185 LookupOrdinaryName,
13186 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013187 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013188 // it contains any previous declaration, except for function parameters in
13189 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013190 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013191 if (isDeclInScope(PrevDecl, CurContext, S)) {
13192 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13193 << D.getIdentifier();
13194 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13195 Invalid = true;
13196 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013197 // Maybe we will complain about the shadowed template parameter.
13198 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013199 }
13200
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013201 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013202 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13203 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013204 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013205 }
13206
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013207 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013208 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013209 D.getIdentifierLoc(),
13210 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013211 if (Invalid)
13212 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013213
Sebastian Redl54c04d42008-12-22 19:15:10 +000013214 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013215 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013216 PushOnScopeChains(ExDecl, S);
13217 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013218 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013219
Douglas Gregor758a8692009-06-17 21:51:59 +000013220 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013221 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013222}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013223
Abramo Bagnaraea947882011-03-08 16:41:52 +000013224Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013225 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013226 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013227 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013228 StringLiteral *AssertMessage =
13229 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013230
Richard Smithded9c2e2012-07-11 22:37:56 +000013231 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013232 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013233
13234 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13235 AssertMessage, RParenLoc, false);
13236}
13237
13238Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13239 Expr *AssertExpr,
13240 StringLiteral *AssertMessage,
13241 SourceLocation RParenLoc,
13242 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013243 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013244 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13245 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013246 // In a static_assert-declaration, the constant-expression shall be a
13247 // constant expression that can be contextually converted to bool.
13248 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13249 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013250 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013251
Richard Smith902ca212011-12-14 23:32:26 +000013252 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013253 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013254 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013255 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013256 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013257
Richard Smithded9c2e2012-07-11 22:37:56 +000013258 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013259 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013260 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013261 if (AssertMessage)
13262 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013263 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013264 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013265 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013266 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013267 }
Mike Stump11289f42009-09-09 15:08:12 +000013268
Abramo Bagnaraea947882011-03-08 16:41:52 +000013269 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013270 AssertExpr, AssertMessage, RParenLoc,
13271 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013272
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013273 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013274 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013275}
Sebastian Redlf769df52009-03-24 22:27:57 +000013276
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013277/// \brief Perform semantic analysis of the given friend type declaration.
13278///
13279/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013280FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013281 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013282 TypeSourceInfo *TSInfo) {
13283 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13284
13285 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013286 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013287
Richard Smithc8239732011-10-18 21:39:00 +000013288 // C++03 [class.friend]p2:
13289 // An elaborated-type-specifier shall be used in a friend declaration
13290 // for a class.*
13291 //
13292 // * The class-key of the elaborated-type-specifier is required.
Richard Smith696e3122017-02-23 01:43:54 +000013293 if (!CodeSynthesisContexts.empty()) {
13294 // Do not complain about the form of friend template types during any kind
13295 // of code synthesis. For template instantiation, we will have complained
13296 // when the template was defined.
Nick Lewycky36722d22013-02-06 05:59:33 +000013297 } else {
13298 if (!T->isElaboratedTypeSpecifier()) {
13299 // If we evaluated the type to a record type, suggest putting
13300 // a tag in front.
13301 if (const RecordType *RT = T->getAs<RecordType>()) {
13302 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013303
13304 SmallString<16> InsertionText(" ");
13305 InsertionText += RD->getKindName();
13306
Nick Lewycky36722d22013-02-06 05:59:33 +000013307 Diag(TypeRange.getBegin(),
13308 getLangOpts().CPlusPlus11 ?
13309 diag::warn_cxx98_compat_unelaborated_friend_type :
13310 diag::ext_unelaborated_friend_type)
13311 << (unsigned) RD->getTagKind()
13312 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013313 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013314 InsertionText);
13315 } else {
13316 Diag(FriendLoc,
13317 getLangOpts().CPlusPlus11 ?
13318 diag::warn_cxx98_compat_nonclass_type_friend :
13319 diag::ext_nonclass_type_friend)
13320 << T
13321 << TypeRange;
13322 }
13323 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013324 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013325 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013326 diag::warn_cxx98_compat_enum_friend :
13327 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013328 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013329 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013330 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013331
Nick Lewycky36722d22013-02-06 05:59:33 +000013332 // C++11 [class.friend]p3:
13333 // A friend declaration that does not declare a function shall have one
13334 // of the following forms:
13335 // friend elaborated-type-specifier ;
13336 // friend simple-type-specifier ;
13337 // friend typename-specifier ;
13338 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13339 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13340 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013341
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013342 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013343 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013344 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013345 return FriendDecl::Create(Context, CurContext,
13346 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13347 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013348}
13349
John McCallace48cd2010-10-19 01:40:49 +000013350/// Handle a friend tag declaration where the scope specifier was
13351/// templated.
13352Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13353 unsigned TagSpec, SourceLocation TagLoc,
13354 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013355 IdentifierInfo *Name,
13356 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013357 AttributeList *Attr,
13358 MultiTemplateParamsArg TempParamLists) {
13359 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13360
Richard Smithf445f192017-02-09 21:04:43 +000013361 bool IsMemberSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013362 bool Invalid = false;
13363
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013364 if (TemplateParameterList *TemplateParams =
13365 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013366 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Richard Smithf445f192017-02-09 21:04:43 +000013367 IsMemberSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013368 if (TemplateParams->size() > 0) {
13369 // This is a declaration of a class template.
13370 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013371 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013372
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013373 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13374 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013375 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013376 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013377 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013378 } else {
13379 // The "template<>" header is extraneous.
13380 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13381 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Richard Smithf445f192017-02-09 21:04:43 +000013382 IsMemberSpecialization = true;
John McCallace48cd2010-10-19 01:40:49 +000013383 }
13384 }
13385
Craig Topperc3ec1492014-05-26 06:22:03 +000013386 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013387
John McCallace48cd2010-10-19 01:40:49 +000013388 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013389 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013390 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013391 isAllExplicitSpecializations = false;
13392 break;
13393 }
13394 }
13395
13396 // FIXME: don't ignore attributes.
13397
13398 // If it's explicit specializations all the way down, just forget
13399 // about the template header and build an appropriate non-templated
13400 // friend. TODO: for source fidelity, remember the headers.
13401 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013402 if (SS.isEmpty()) {
13403 bool Owned = false;
13404 bool IsDependent = false;
13405 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013406 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013407 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013408 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013409 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013410 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013411 /*UnderlyingType=*/TypeResult(),
13412 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013413 }
Richard Smith649c7b062014-01-08 00:56:48 +000013414
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013415 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013416 ElaboratedTypeKeyword Keyword
13417 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013418 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013419 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013420 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013421 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013422
13423 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13424 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013425 DependentNameTypeLoc TL =
13426 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013427 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013428 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013429 TL.setNameLoc(NameLoc);
13430 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013431 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013432 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013433 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013434 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013435 }
13436
13437 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013438 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013439 Friend->setAccess(AS_public);
13440 CurContext->addDecl(Friend);
13441 return Friend;
13442 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013443
13444 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13445
13446
John McCallace48cd2010-10-19 01:40:49 +000013447
13448 // Handle the case of a templated-scope friend class. e.g.
13449 // template <class T> class A<T>::B;
13450 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013451 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13452 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013453 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13454 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13455 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013456 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013457 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013458 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013459 TL.setNameLoc(NameLoc);
13460
13461 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013462 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013463 Friend->setAccess(AS_public);
13464 Friend->setUnsupportedFriend(true);
13465 CurContext->addDecl(Friend);
13466 return Friend;
13467}
13468
13469
John McCall11083da2009-09-16 22:47:08 +000013470/// Handle a friend type declaration. This works in tandem with
13471/// ActOnTag.
13472///
13473/// Notes on friend class templates:
13474///
13475/// We generally treat friend class declarations as if they were
13476/// declaring a class. So, for example, the elaborated type specifier
13477/// in a friend declaration is required to obey the restrictions of a
13478/// class-head (i.e. no typedefs in the scope chain), template
13479/// parameters are required to match up with simple template-ids, &c.
13480/// However, unlike when declaring a template specialization, it's
13481/// okay to refer to a template specialization without an empty
13482/// template parameter declaration, e.g.
13483/// friend class A<T>::B<unsigned>;
13484/// We permit this as a special case; if there are any template
13485/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013486/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013487Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013488 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013489 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013490
13491 assert(DS.isFriendSpecified());
13492 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13493
John McCall11083da2009-09-16 22:47:08 +000013494 // Try to convert the decl specifier to a type. This works for
13495 // friend templates because ActOnTag never produces a ClassTemplateDecl
13496 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013497 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013498 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13499 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013500 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013501 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013502
Douglas Gregor6c110f32010-12-16 01:14:37 +000013503 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013504 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013505
John McCall11083da2009-09-16 22:47:08 +000013506 // This is definitely an error in C++98. It's probably meant to
13507 // be forbidden in C++0x, too, but the specification is just
13508 // poorly written.
13509 //
13510 // The problem is with declarations like the following:
13511 // template <T> friend A<T>::foo;
13512 // where deciding whether a class C is a friend or not now hinges
13513 // on whether there exists an instantiation of A that causes
13514 // 'foo' to equal C. There are restrictions on class-heads
13515 // (which we declare (by fiat) elaborated friend declarations to
13516 // be) that makes this tractable.
13517 //
13518 // FIXME: handle "template <> friend class A<T>;", which
13519 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013520 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013521 Diag(Loc, diag::err_tagless_friend_type_template)
13522 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013523 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013524 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013525
John McCallaa74a0c2009-08-28 07:59:38 +000013526 // C++98 [class.friend]p1: A friend of a class is a function
13527 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013528 // This is fixed in DR77, which just barely didn't make the C++03
13529 // deadline. It's also a very silly restriction that seriously
13530 // affects inner classes and which nobody else seems to implement;
13531 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013532 //
13533 // But note that we could warn about it: it's always useless to
13534 // friend one of your own members (it's not, however, worthless to
13535 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013536
John McCall11083da2009-09-16 22:47:08 +000013537 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013538 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013539 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013540 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013541 TSI,
John McCall11083da2009-09-16 22:47:08 +000013542 DS.getFriendSpecLoc());
13543 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013544 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013545
13546 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013547 return nullptr;
13548
John McCall11083da2009-09-16 22:47:08 +000013549 D->setAccess(AS_public);
13550 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013551
John McCall48871652010-08-21 09:40:31 +000013552 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013553}
13554
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013555NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13556 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013557 const DeclSpec &DS = D.getDeclSpec();
13558
13559 assert(DS.isFriendSpecified());
13560 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13561
13562 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013563 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013564
13565 // C++ [class.friend]p1
13566 // A friend of a class is a function or class....
13567 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013568 // It *doesn't* see through dependent types, which is correct
13569 // according to [temp.arg.type]p3:
13570 // If a declaration acquires a function type through a
13571 // type dependent on a template-parameter and this causes
13572 // a declaration that does not use the syntactic form of a
13573 // function declarator to have a function type, the program
13574 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013575 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013576 Diag(Loc, diag::err_unexpected_friend);
13577
13578 // It might be worthwhile to try to recover by creating an
13579 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013580 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013581 }
13582
13583 // C++ [namespace.memdef]p3
13584 // - If a friend declaration in a non-local class first declares a
13585 // class or function, the friend class or function is a member
13586 // of the innermost enclosing namespace.
13587 // - The name of the friend is not found by simple name lookup
13588 // until a matching declaration is provided in that namespace
13589 // scope (either before or after the class declaration granting
13590 // friendship).
13591 // - If a friend function is called, its name may be found by the
13592 // name lookup that considers functions from namespaces and
13593 // classes associated with the types of the function arguments.
13594 // - When looking for a prior declaration of a class or a function
13595 // declared as a friend, scopes outside the innermost enclosing
13596 // namespace scope are not considered.
13597
John McCallde3fd222010-10-12 23:13:28 +000013598 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013599 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13600 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013601 assert(Name);
13602
Douglas Gregor6c110f32010-12-16 01:14:37 +000013603 // Check for unexpanded parameter packs.
13604 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13605 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13606 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013607 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013608
John McCall07e91c02009-08-06 02:15:43 +000013609 // The context we found the declaration in, or in which we should
13610 // create the declaration.
13611 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013612 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013613 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013614 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013615
Richard Smith114394f2013-08-09 04:35:01 +000013616 // There are five cases here.
13617 // - There's no scope specifier and we're in a local class. Only look
13618 // for functions declared in the immediately-enclosing block scope.
13619 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013620 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013621 if ((SS.isInvalid() || !SS.isSet()) &&
13622 (FunctionContainingLocalClass =
13623 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13624 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013625 // If a friend declaration appears in a local class and the name
13626 // specified is an unqualified name, a prior declaration is
13627 // looked up without considering scopes that are outside the
13628 // innermost enclosing non-class scope. For a friend function
13629 // declaration, if there is no prior declaration, the program is
13630 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013631
13632 // Find the innermost enclosing non-class scope. This is the block
13633 // scope containing the local class definition (or for a nested class,
13634 // the outer local class).
13635 DCScope = S->getFnParent();
13636
13637 // Look up the function name in the scope.
13638 Previous.clear(LookupLocalFriendName);
13639 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13640
13641 if (!Previous.empty()) {
13642 // All possible previous declarations must have the same context:
13643 // either they were declared at block scope or they are members of
13644 // one of the enclosing local classes.
13645 DC = Previous.getRepresentativeDecl()->getDeclContext();
13646 } else {
13647 // This is ill-formed, but provide the context that we would have
13648 // declared the function in, if we were permitted to, for error recovery.
13649 DC = FunctionContainingLocalClass;
13650 }
Richard Smith541b38b2013-09-20 01:15:31 +000013651 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013652
13653 // C++ [class.friend]p6:
13654 // A function can be defined in a friend declaration of a class if and
13655 // only if the class is a non-local class (9.8), the function name is
13656 // unqualified, and the function has namespace scope.
13657 if (D.isFunctionDefinition()) {
13658 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13659 }
13660
13661 // - There's no scope specifier, in which case we just go to the
13662 // appropriate scope and look for a function or function template
13663 // there as appropriate.
13664 } else if (SS.isInvalid() || !SS.isSet()) {
13665 // C++11 [namespace.memdef]p3:
13666 // If the name in a friend declaration is neither qualified nor
13667 // a template-id and the declaration is a function or an
13668 // elaborated-type-specifier, the lookup to determine whether
13669 // the entity has been previously declared shall not consider
13670 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013671 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013672
John McCallf7cfb222010-10-13 05:45:15 +000013673 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013674 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013675
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013676 // Skip class contexts. If someone can cite chapter and verse
13677 // for this behavior, that would be nice --- it's what GCC and
13678 // EDG do, and it seems like a reasonable intent, but the spec
13679 // really only says that checks for unqualified existing
13680 // declarations should stop at the nearest enclosing namespace,
13681 // not that they should only consider the nearest enclosing
13682 // namespace.
13683 while (DC->isRecord())
13684 DC = DC->getParent();
13685
13686 DeclContext *LookupDC = DC;
13687 while (LookupDC->isTransparentContext())
13688 LookupDC = LookupDC->getParent();
13689
13690 while (true) {
13691 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013692
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013693 if (!Previous.empty()) {
13694 DC = LookupDC;
13695 break;
John McCallf4776592010-10-14 22:22:28 +000013696 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013697
13698 if (isTemplateId) {
13699 if (isa<TranslationUnitDecl>(LookupDC)) break;
13700 } else {
13701 if (LookupDC->isFileContext()) break;
13702 }
13703 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013704 }
13705
John McCallccbc0322010-10-13 06:22:15 +000013706 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013707
John McCallde3fd222010-10-12 23:13:28 +000013708 // - There's a non-dependent scope specifier, in which case we
13709 // compute it and do a previous lookup there for a function
13710 // or function template.
13711 } else if (!SS.getScopeRep()->isDependent()) {
13712 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013713 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013714
Craig Topperc3ec1492014-05-26 06:22:03 +000013715 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013716
13717 LookupQualifiedName(Previous, DC);
13718
13719 // Ignore things found implicitly in the wrong scope.
13720 // TODO: better diagnostics for this case. Suggesting the right
13721 // qualified scope would be nice...
13722 LookupResult::Filter F = Previous.makeFilter();
13723 while (F.hasNext()) {
13724 NamedDecl *D = F.next();
13725 if (!DC->InEnclosingNamespaceSetOf(
13726 D->getDeclContext()->getRedeclContext()))
13727 F.erase();
13728 }
13729 F.done();
13730
13731 if (Previous.empty()) {
13732 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013733 Diag(Loc, diag::err_qualified_friend_not_found)
13734 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013735 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013736 }
13737
13738 // C++ [class.friend]p1: A friend of a class is a function or
13739 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013740 if (DC->Equals(CurContext))
13741 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013742 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013743 diag::warn_cxx98_compat_friend_is_member :
13744 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013745
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013746 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013747 // C++ [class.friend]p6:
13748 // A function can be defined in a friend declaration of a class if and
13749 // only if the class is a non-local class (9.8), the function name is
13750 // unqualified, and the function has namespace scope.
13751 SemaDiagnosticBuilder DB
13752 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13753
13754 DB << SS.getScopeRep();
13755 if (DC->isFileContext())
13756 DB << FixItHint::CreateRemoval(SS.getRange());
13757 SS.clear();
13758 }
John McCallde3fd222010-10-12 23:13:28 +000013759
13760 // - There's a scope specifier that does not match any template
13761 // parameter lists, in which case we use some arbitrary context,
13762 // create a method or method template, and wait for instantiation.
13763 // - There's a scope specifier that does match some template
13764 // parameter lists, which we don't handle right now.
13765 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013766 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013767 // C++ [class.friend]p6:
13768 // A function can be defined in a friend declaration of a class if and
13769 // only if the class is a non-local class (9.8), the function name is
13770 // unqualified, and the function has namespace scope.
13771 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13772 << SS.getScopeRep();
13773 }
13774
John McCallde3fd222010-10-12 23:13:28 +000013775 DC = CurContext;
13776 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013777 }
David Majnemere14d5302015-09-30 22:07:43 +000013778
John McCallf7cfb222010-10-13 05:45:15 +000013779 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013780 int DiagArg = -1;
13781 switch (D.getName().getKind()) {
13782 case UnqualifiedId::IK_ConstructorTemplateId:
13783 case UnqualifiedId::IK_ConstructorName:
13784 DiagArg = 0;
13785 break;
13786 case UnqualifiedId::IK_DestructorName:
13787 DiagArg = 1;
13788 break;
13789 case UnqualifiedId::IK_ConversionFunctionId:
13790 DiagArg = 2;
13791 break;
Richard Smith35845152017-02-07 01:37:30 +000013792 case UnqualifiedId::IK_DeductionGuideName:
13793 DiagArg = 3;
13794 break;
David Majnemere14d5302015-09-30 22:07:43 +000013795 case UnqualifiedId::IK_Identifier:
13796 case UnqualifiedId::IK_ImplicitSelfParam:
13797 case UnqualifiedId::IK_LiteralOperatorId:
13798 case UnqualifiedId::IK_OperatorFunctionId:
13799 case UnqualifiedId::IK_TemplateId:
13800 break;
David Majnemere14d5302015-09-30 22:07:43 +000013801 }
John McCall07e91c02009-08-06 02:15:43 +000013802 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013803 if (DiagArg >= 0) {
13804 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013805 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013806 }
John McCall07e91c02009-08-06 02:15:43 +000013807 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013808
Douglas Gregordd847ba2011-11-03 16:37:14 +000013809 // FIXME: This is an egregious hack to cope with cases where the scope stack
13810 // does not contain the declaration context, i.e., in an out-of-line
13811 // definition of a class.
13812 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13813 if (!DCScope) {
13814 FakeDCScope.setEntity(DC);
13815 DCScope = &FakeDCScope;
13816 }
Richard Smith114394f2013-08-09 04:35:01 +000013817
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013818 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013819 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013820 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013821 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013822
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013823 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013824
Richard Smith114394f2013-08-09 04:35:01 +000013825 // If we performed typo correction, we might have added a scope specifier
13826 // and changed the decl context.
13827 DC = ND->getDeclContext();
13828
John McCall759e32b2009-08-31 22:39:49 +000013829 // Add the function declaration to the appropriate lookup tables,
13830 // adjusting the redeclarations list as necessary. We don't
13831 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013832 //
John McCall759e32b2009-08-31 22:39:49 +000013833 // Also update the scope-based lookup if the target context's
13834 // lookup context is in lexical scope.
13835 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013836 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013837 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013838 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013839 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013840 }
John McCallaa74a0c2009-08-28 07:59:38 +000013841
13842 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013843 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013844 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013845 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013846 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013847
John McCalla0a96892012-08-10 03:15:35 +000013848 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013849 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013850 } else {
13851 if (DC->isRecord()) CheckFriendAccess(ND);
13852
John McCall2c2eb122010-10-16 06:59:13 +000013853 FunctionDecl *FD;
13854 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13855 FD = FTD->getTemplatedDecl();
13856 else
13857 FD = cast<FunctionDecl>(ND);
13858
David Majnemer502b0ed2013-06-25 23:09:30 +000013859 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13860 // default argument expression, that declaration shall be a definition
13861 // and shall be the only declaration of the function or function
13862 // template in the translation unit.
13863 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013864 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013865 // if we're in a dependent context. If the function is known to be a
13866 // redeclaration, we will have narrowed Previous down to the right decl.
13867 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013868 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013869 Diag(Previous.getRepresentativeDecl()->getLocation(),
13870 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013871 } else if (!D.isFunctionDefinition())
13872 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13873 }
13874
John McCall2c2eb122010-10-16 06:59:13 +000013875 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013876 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13877 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13878 << SS.getScopeRep() << SS.getRange()
13879 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013880 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013881 }
John McCall2c2eb122010-10-16 06:59:13 +000013882 }
John McCallde3fd222010-10-12 23:13:28 +000013883
John McCall48871652010-08-21 09:40:31 +000013884 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013885}
13886
John McCall48871652010-08-21 09:40:31 +000013887void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13888 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013889
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013890 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013891 if (!Fn) {
13892 Diag(DelLoc, diag::err_deleted_non_function);
13893 return;
13894 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013895
Douglas Gregorec9fd132012-01-14 16:38:05 +000013896 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013897 // Don't consider the implicit declaration we generate for explicit
13898 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013899 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13900 Prev->getPreviousDecl()) &&
13901 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013902 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013903 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13904 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13905 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013906 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013907 // If the declaration wasn't the first, we delete the function anyway for
13908 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013909 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013910 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013911
Nico Rieck9de0a572014-05-29 16:51:19 +000013912 // dllimport/dllexport cannot be deleted.
13913 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13914 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13915 Fn->setInvalidDecl();
13916 }
13917
Richard Smithb4d2a152013-04-02 19:38:47 +000013918 if (Fn->isDeleted())
13919 return;
13920
13921 // See if we're deleting a function which is already known to override a
13922 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013923 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013924 bool IssuedDiagnostic = false;
13925 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13926 E = MD->end_overridden_methods();
13927 I != E; ++I) {
13928 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13929 if (!IssuedDiagnostic) {
13930 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13931 IssuedDiagnostic = true;
13932 }
13933 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13934 }
13935 }
Richard Smithf3cec652016-10-31 18:18:29 +000013936 // If this function was implicitly deleted because it was defaulted,
13937 // explain why it was deleted.
13938 if (IssuedDiagnostic && MD->isDefaulted())
13939 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13940 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000013941 }
13942
Richard Smithb63b6ee2014-01-22 01:43:19 +000013943 // C++11 [basic.start.main]p3:
13944 // A program that defines main as deleted [...] is ill-formed.
13945 if (Fn->isMain())
13946 Diag(DelLoc, diag::err_deleted_main);
13947
Eric Fiselier525a3512016-10-31 23:07:15 +000013948 // C++11 [dcl.fct.def.delete]p4:
13949 // A deleted function is implicitly inline.
13950 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013951 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013952}
Sebastian Redl4c018662009-04-27 21:33:24 +000013953
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013954void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013955 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013956
13957 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013958 if (MD->getParent()->isDependentType()) {
13959 MD->setDefaulted();
13960 MD->setExplicitlyDefaulted();
13961 return;
13962 }
13963
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013964 CXXSpecialMember Member = getSpecialMember(MD);
13965 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013966 if (!MD->isInvalidDecl())
13967 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013968 return;
13969 }
13970
13971 MD->setDefaulted();
13972 MD->setExplicitlyDefaulted();
13973
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013974 // If this definition appears within the record, do the checking when
13975 // the record is complete.
13976 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013977 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013978 // Ask the template instantiation pattern that actually had the
13979 // '= default' on it.
13980 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013981
Richard Smith3901dfe2013-03-27 00:22:47 +000013982 // If the method was defaulted on its first declaration, we will have
13983 // already performed the checking in CheckCompletedCXXClass. Such a
13984 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013985 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013986 return;
13987
Richard Smithd3b5c9082012-07-27 04:22:15 +000013988 CheckExplicitlyDefaultedSpecialMember(MD);
13989
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013990 if (!MD->isInvalidDecl())
13991 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013992 } else {
13993 Diag(DefaultLoc, diag::err_default_special_members);
13994 }
13995}
13996
Sebastian Redl4c018662009-04-27 21:33:24 +000013997static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013998 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013999 if (!SubStmt)
14000 continue;
14001 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014002 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000014003 diag::err_return_in_constructor_handler);
14004 if (!isa<Expr>(SubStmt))
14005 SearchForReturnInStmt(Self, SubStmt);
14006 }
14007}
14008
14009void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14010 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14011 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14012 SearchForReturnInStmt(*this, Handler);
14013 }
14014}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014015
David Blaikie68f71a32013-01-18 23:03:15 +000014016bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000014017 const CXXMethodDecl *Old) {
14018 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14019 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14020
14021 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14022
14023 // If the calling conventions match, everything is fine
14024 if (NewCC == OldCC)
14025 return false;
14026
Hans Wennborg2545efe2013-12-11 17:42:11 +000014027 // If the calling conventions mismatch because the new function is static,
14028 // suppress the calling convention mismatch error; the error about static
14029 // function override (err_static_overrides_virtual from
14030 // Sema::CheckFunctionDeclaration) is more clear.
14031 if (New->getStorageClass() == SC_Static)
14032 return false;
14033
Reid Kleckner78af0702013-08-27 23:08:25 +000014034 Diag(New->getLocation(),
14035 diag::err_conflicting_overriding_cc_attributes)
14036 << New->getDeclName() << New->getType() << Old->getType();
14037 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14038 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000014039}
14040
Mike Stump11289f42009-09-09 15:08:12 +000014041bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014042 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000014043 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14044 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014045
Chandler Carruth284bb2e2010-02-15 11:53:20 +000014046 if (Context.hasSameType(NewTy, OldTy) ||
14047 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014048 return false;
Mike Stump11289f42009-09-09 15:08:12 +000014049
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014050 // Check if the return types are covariant
14051 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000014052
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014053 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014054 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14055 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014056 NewClassTy = NewPT->getPointeeType();
14057 OldClassTy = OldPT->getPointeeType();
14058 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014059 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14060 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14061 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14062 NewClassTy = NewRT->getPointeeType();
14063 OldClassTy = OldRT->getPointeeType();
14064 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014065 }
14066 }
Mike Stump11289f42009-09-09 15:08:12 +000014067
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014068 // The return types aren't either both pointers or references to a class type.
14069 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014070 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014071 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014072 << New->getDeclName() << NewTy << OldTy
14073 << New->getReturnTypeSourceRange();
14074 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14075 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014076
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014077 return true;
14078 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014079
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014080 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014081 // C++14 [class.virtual]p8:
14082 // If the class type in the covariant return type of D::f differs from
14083 // that of B::f, the class type in the return type of D::f shall be
14084 // complete at the point of declaration of D::f or shall be the class
14085 // type D.
14086 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14087 if (!RT->isBeingDefined() &&
14088 RequireCompleteType(New->getLocation(), NewClassTy,
14089 diag::err_covariant_return_incomplete,
14090 New->getDeclName()))
14091 return true;
14092 }
14093
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014094 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014095 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014096 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14097 << New->getDeclName() << NewTy << OldTy
14098 << New->getReturnTypeSourceRange();
14099 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14100 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014101 return true;
14102 }
Mike Stump11289f42009-09-09 15:08:12 +000014103
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014104 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014105 if (CheckDerivedToBaseConversion(
14106 NewClassTy, OldClassTy,
14107 diag::err_covariant_return_inaccessible_base,
14108 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14109 New->getLocation(), New->getReturnTypeSourceRange(),
14110 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014111 // FIXME: this note won't trigger for delayed access control
14112 // diagnostics, and it's impossible to get an undelayed error
14113 // here from access control during the original parse because
14114 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014115 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14116 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014117 return true;
14118 }
14119 }
Mike Stump11289f42009-09-09 15:08:12 +000014120
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014121 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014122 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014123 Diag(New->getLocation(),
14124 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014125 << New->getDeclName() << NewTy << OldTy
14126 << New->getReturnTypeSourceRange();
14127 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14128 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014129 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014130 }
Mike Stump11289f42009-09-09 15:08:12 +000014131
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014132
14133 // The new class type must have the same or less qualifiers as the old type.
14134 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14135 Diag(New->getLocation(),
14136 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014137 << New->getDeclName() << NewTy << OldTy
14138 << New->getReturnTypeSourceRange();
14139 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14140 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014141 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014142 }
Mike Stump11289f42009-09-09 15:08:12 +000014143
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014144 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014145}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014146
Douglas Gregor21920e372009-12-01 17:24:26 +000014147/// \brief Mark the given method pure.
14148///
14149/// \param Method the method to be marked pure.
14150///
14151/// \param InitRange the source range that covers the "0" initializer.
14152bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014153 SourceLocation EndLoc = InitRange.getEnd();
14154 if (EndLoc.isValid())
14155 Method->setRangeEnd(EndLoc);
14156
Douglas Gregor21920e372009-12-01 17:24:26 +000014157 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14158 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014159 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014160 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014161
14162 if (!Method->isInvalidDecl())
14163 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14164 << Method->getDeclName() << InitRange;
14165 return true;
14166}
14167
Richard Smith9ba0fec2015-06-30 01:28:56 +000014168void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14169 if (D->getFriendObjectKind())
14170 Diag(D->getLocation(), diag::err_pure_friend);
14171 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14172 CheckPureMethod(M, ZeroLoc);
14173 else
14174 Diag(D->getLocation(), diag::err_illegal_initializer);
14175}
14176
Douglas Gregor926410d2012-02-21 02:22:07 +000014177/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014178static bool isStaticDataMember(const Decl *D) {
14179 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14180 return Var->isStaticDataMember();
14181
14182 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014183}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014184
John McCall1f4ee7b2009-12-19 09:28:58 +000014185/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14186/// an initializer for the out-of-line declaration 'Dcl'. The scope
14187/// is a fresh scope pushed for just this purpose.
14188///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014189/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14190/// static data member of class X, names should be looked up in the scope of
14191/// class X.
John McCall48871652010-08-21 09:40:31 +000014192void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014193 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014194 if (!D || D->isInvalidDecl())
14195 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014196
Richard Smitha2302242013-12-05 07:51:02 +000014197 // We will always have a nested name specifier here, but this declaration
14198 // might not be out of line if the specifier names the current namespace:
14199 // extern int n;
14200 // int ::n = 0;
14201 if (D->isOutOfLine())
14202 EnterDeclaratorContext(S, D->getDeclContext());
14203
Douglas Gregor926410d2012-02-21 02:22:07 +000014204 // If we are parsing the initializer for a static data member, push a
14205 // new expression evaluation context that is associated with this static
14206 // data member.
14207 if (isStaticDataMember(D))
14208 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014209}
14210
14211/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014212/// initializer for the out-of-line declaration 'D'.
14213void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014214 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014215 if (!D || D->isInvalidDecl())
14216 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014217
Douglas Gregor926410d2012-02-21 02:22:07 +000014218 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014219 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014220
Richard Smitha2302242013-12-05 07:51:02 +000014221 if (D->isOutOfLine())
14222 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014223}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014224
14225/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14226/// C++ if/switch/while/for statement.
14227/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014228DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014229 // C++ 6.4p2:
14230 // The declarator shall not specify a function or an array.
14231 // The type-specifier-seq shall not contain typedef and shall not declare a
14232 // new class or enumeration.
14233 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14234 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014235
14236 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014237 if (!Dcl)
14238 return true;
14239
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014240 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14241 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014242 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014243 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014244 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014245
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014246 return Dcl;
14247}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014248
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014249void Sema::LoadExternalVTableUses() {
14250 if (!ExternalSource)
14251 return;
14252
14253 SmallVector<ExternalVTableUse, 4> VTables;
14254 ExternalSource->ReadUsedVTables(VTables);
14255 SmallVector<VTableUse, 4> NewUses;
14256 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14257 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14258 = VTablesUsed.find(VTables[I].Record);
14259 // Even if a definition wasn't required before, it may be required now.
14260 if (Pos != VTablesUsed.end()) {
14261 if (!Pos->second && VTables[I].DefinitionRequired)
14262 Pos->second = true;
14263 continue;
14264 }
14265
14266 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14267 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14268 }
14269
14270 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14271}
14272
Douglas Gregor88d292c2010-05-13 16:44:06 +000014273void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14274 bool DefinitionRequired) {
14275 // Ignore any vtable uses in unevaluated operands or for classes that do
14276 // not have a vtable.
14277 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014278 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014279 return;
14280
Douglas Gregor88d292c2010-05-13 16:44:06 +000014281 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014282 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014283 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14284 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14285 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14286 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014287 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014288 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014289 // list, since we may have already processed the first entry.
14290 if (DefinitionRequired && !Pos.first->second) {
14291 Pos.first->second = true;
14292 } else {
14293 // Otherwise, we can early exit.
14294 return;
14295 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014296 } else {
14297 // The Microsoft ABI requires that we perform the destructor body
14298 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14299 // the deleting destructor is emitted with the vtable, not with the
14300 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014301 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014302 CXXDestructorDecl *DD = Class->getDestructor();
14303 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14304 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14305 // If this is an out-of-line declaration, marking it referenced will
14306 // not do anything. Manually call CheckDestructor to look up operator
14307 // delete().
14308 ContextRAII SavedContext(*this, DD);
14309 CheckDestructor(DD);
14310 } else {
14311 MarkFunctionReferenced(Loc, Class->getDestructor());
14312 }
Hans Wennborg34804352016-04-13 20:21:15 +000014313 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014314 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014315 }
14316
14317 // Local classes need to have their virtual members marked
14318 // immediately. For all other classes, we mark their virtual members
14319 // at the end of the translation unit.
14320 if (Class->isLocalClass())
14321 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014322 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014323 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014324}
14325
Douglas Gregor88d292c2010-05-13 16:44:06 +000014326bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014327 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014328 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014329 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014330
Douglas Gregor88d292c2010-05-13 16:44:06 +000014331 // Note: The VTableUses vector could grow as a result of marking
14332 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014333 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014334 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014335 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014336 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014337 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014338 if (!Class)
14339 continue;
Reid Klecknerb792e062016-12-06 21:44:41 +000014340 TemplateSpecializationKind ClassTSK =
14341 Class->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014342
14343 SourceLocation Loc = VTableUses[I].second;
14344
Richard Smithd3b5c9082012-07-27 04:22:15 +000014345 bool DefineVTable = true;
14346
Douglas Gregor88d292c2010-05-13 16:44:06 +000014347 // If this class has a key function, but that key function is
14348 // defined in another translation unit, we don't need to emit the
14349 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014350 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014351 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014352 // The key function is in another translation unit.
14353 DefineVTable = false;
14354 TemplateSpecializationKind TSK =
14355 KeyFunction->getTemplateSpecializationKind();
14356 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14357 TSK != TSK_ImplicitInstantiation &&
14358 "Instantiations don't have key functions");
14359 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014360 } else if (!KeyFunction) {
14361 // If we have a class with no key function that is the subject
14362 // of an explicit instantiation declaration, suppress the
14363 // vtable; it will live with the explicit instantiation
14364 // definition.
Reid Klecknerb792e062016-12-06 21:44:41 +000014365 bool IsExplicitInstantiationDeclaration =
14366 ClassTSK == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014367 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014368 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014369 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014370 if (TSK == TSK_ExplicitInstantiationDeclaration)
14371 IsExplicitInstantiationDeclaration = true;
14372 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14373 IsExplicitInstantiationDeclaration = false;
14374 break;
14375 }
14376 }
14377
14378 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014379 DefineVTable = false;
14380 }
14381
14382 // The exception specifications for all virtual members may be needed even
14383 // if we are not providing an authoritative form of the vtable in this TU.
14384 // We may choose to emit it available_externally anyway.
14385 if (!DefineVTable) {
14386 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14387 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014388 }
14389
14390 // Mark all of the virtual members of this class as referenced, so
14391 // that we can build a vtable. Then, tell the AST consumer that a
14392 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014393 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014394 MarkVirtualMembersReferenced(Loc, Class);
14395 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014396 if (VTablesUsed[Canonical])
14397 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014398
Reid Klecknerb792e062016-12-06 21:44:41 +000014399 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14400 // no key function or the key function is inlined. Don't warn in C++ ABIs
14401 // that lack key functions, since the user won't be able to make one.
14402 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14403 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014404 const FunctionDecl *KeyFunctionDef = nullptr;
Reid Klecknerb792e062016-12-06 21:44:41 +000014405 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14406 KeyFunctionDef->isInlined())) {
14407 Diag(Class->getLocation(),
14408 ClassTSK == TSK_ExplicitInstantiationDefinition
14409 ? diag::warn_weak_template_vtable
14410 : diag::warn_weak_vtable)
14411 << Class;
14412 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014413 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014414 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014415 VTableUses.clear();
14416
Douglas Gregor97509692011-04-22 22:25:37 +000014417 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014418}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014419
Richard Smithd3b5c9082012-07-27 04:22:15 +000014420void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14421 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014422 for (const auto *I : RD->methods())
14423 if (I->isVirtual() && !I->isPure())
14424 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014425}
14426
Rafael Espindola5b334082010-03-26 00:36:59 +000014427void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14428 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014429 // Mark all functions which will appear in RD's vtable as used.
14430 CXXFinalOverriderMap FinalOverriders;
14431 RD->getFinalOverriders(FinalOverriders);
14432 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14433 E = FinalOverriders.end();
14434 I != E; ++I) {
14435 for (OverridingMethods::const_iterator OI = I->second.begin(),
14436 OE = I->second.end();
14437 OI != OE; ++OI) {
14438 assert(OI->second.size() > 0 && "no final overrider");
14439 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014440
Richard Smith4ff9ff92012-07-07 06:59:51 +000014441 // C++ [basic.def.odr]p2:
14442 // [...] A virtual member function is used if it is not pure. [...]
14443 if (!Overrider->isPure())
14444 MarkFunctionReferenced(Loc, Overrider);
14445 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014446 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014447
14448 // Only classes that have virtual bases need a VTT.
14449 if (RD->getNumVBases() == 0)
14450 return;
14451
Aaron Ballman574705e2014-03-13 15:41:46 +000014452 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014453 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014454 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014455 if (Base->getNumVBases() == 0)
14456 continue;
14457 MarkVirtualMembersReferenced(Loc, Base);
14458 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014459}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014460
14461/// SetIvarInitializers - This routine builds initialization ASTs for the
14462/// Objective-C implementation whose ivars need be initialized.
14463void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014464 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014465 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014466 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014467 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014468 CollectIvarsToConstructOrDestruct(OID, ivars);
14469 if (ivars.empty())
14470 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014471 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014472 for (unsigned i = 0; i < ivars.size(); i++) {
14473 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014474 if (Field->isInvalidDecl())
14475 continue;
14476
Alexis Hunt1d792652011-01-08 20:30:50 +000014477 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014478 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14479 InitializationKind InitKind =
14480 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014481
14482 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14483 ExprResult MemberInit =
14484 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014485 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014486 // Note, MemberInit could actually come back empty if no initialization
14487 // is required (e.g., because it would call a trivial default constructor)
14488 if (!MemberInit.get() || MemberInit.isInvalid())
14489 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014490
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014491 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014492 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14493 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014494 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014495 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014496 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014497
14498 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014499 if (const RecordType *RecordTy =
14500 Context.getBaseElementType(Field->getType())
14501 ->getAs<RecordType>()) {
14502 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014503 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014504 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014505 CheckDestructorAccess(Field->getLocation(), Destructor,
14506 PDiag(diag::err_access_dtor_ivar)
14507 << Context.getBaseElementType(Field->getType()));
14508 }
14509 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014510 }
14511 ObjCImplementation->setIvarInitializers(Context,
14512 AllToInit.data(), AllToInit.size());
14513 }
14514}
Alexis Hunt6118d662011-05-04 05:57:24 +000014515
Alexis Hunt27a761d2011-05-04 23:29:54 +000014516static
14517void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14518 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14519 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14520 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14521 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014522 if (Ctor->isInvalidDecl())
14523 return;
14524
Richard Smith802c4b72012-08-23 06:16:52 +000014525 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14526
14527 // Target may not be determinable yet, for instance if this is a dependent
14528 // call in an uninstantiated template.
14529 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014530 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014531 (void)Target->hasBody(FNTarget);
14532 Target = const_cast<CXXConstructorDecl*>(
14533 cast_or_null<CXXConstructorDecl>(FNTarget));
14534 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014535
14536 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14537 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014538 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014539
David Blaikie82e95a32014-11-19 07:49:47 +000014540 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014541 return;
14542
14543 // We know that beyond here, we aren't chaining into a cycle.
14544 if (!Target || !Target->isDelegatingConstructor() ||
14545 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014546 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014547 Current.clear();
14548 // We've hit a cycle.
14549 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14550 Current.count(TCanonical)) {
14551 // If we haven't diagnosed this cycle yet, do so now.
14552 if (!Invalid.count(TCanonical)) {
14553 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014554 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014555 << Ctor;
14556
Richard Smith802c4b72012-08-23 06:16:52 +000014557 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014558 if (TCanonical != Canonical)
14559 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14560
14561 CXXConstructorDecl *C = Target;
14562 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014563 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014564 (void)C->getTargetConstructor()->hasBody(FNTarget);
14565 assert(FNTarget && "Ctor cycle through bodiless function");
14566
Richard Smith802c4b72012-08-23 06:16:52 +000014567 C = const_cast<CXXConstructorDecl*>(
14568 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014569 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14570 }
14571 }
14572
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014573 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014574 Current.clear();
14575 } else {
14576 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14577 }
14578}
14579
14580
Alexis Hunt6118d662011-05-04 05:57:24 +000014581void Sema::CheckDelegatingCtorCycles() {
14582 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14583
Douglas Gregorbae31202011-07-27 21:57:17 +000014584 for (DelegatingCtorDeclsType::iterator
14585 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014586 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014587 I != E; ++I)
14588 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014589
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014590 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14591 CE = Invalid.end();
14592 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014593 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014594}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014595
Douglas Gregor3024f072012-04-16 07:05:22 +000014596namespace {
14597 /// \brief AST visitor that finds references to the 'this' expression.
14598 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14599 Sema &S;
14600
14601 public:
14602 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14603
14604 bool VisitCXXThisExpr(CXXThisExpr *E) {
14605 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14606 << E->isImplicit();
14607 return false;
14608 }
14609 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014610}
Douglas Gregor3024f072012-04-16 07:05:22 +000014611
14612bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14613 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14614 if (!TSInfo)
14615 return false;
14616
14617 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014618 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014619 if (!ProtoTL)
14620 return false;
14621
14622 // C++11 [expr.prim.general]p3:
14623 // [The expression this] shall not appear before the optional
14624 // cv-qualifier-seq and it shall not appear within the declaration of a
14625 // static member function (although its type and value category are defined
14626 // within a static member function as they are within a non-static member
14627 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014628 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014629 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014630 FindCXXThisExpr Finder(*this);
14631
14632 // If the return type came after the cv-qualifier-seq, check it now.
14633 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014634 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014635 return true;
14636
14637 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014638 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14639 return true;
14640
14641 return checkThisInStaticMemberFunctionAttributes(Method);
14642}
14643
14644bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14645 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14646 if (!TSInfo)
14647 return false;
14648
14649 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014650 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014651 if (!ProtoTL)
14652 return false;
14653
David Blaikie6adc78e2013-02-18 22:06:02 +000014654 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014655 FindCXXThisExpr Finder(*this);
14656
Douglas Gregor3024f072012-04-16 07:05:22 +000014657 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014658 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014659 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014660 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014661 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014662 case EST_DynamicNone:
14663 case EST_MSAny:
14664 case EST_None:
14665 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014666
Douglas Gregor3024f072012-04-16 07:05:22 +000014667 case EST_ComputedNoexcept:
14668 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14669 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014670
Douglas Gregor3024f072012-04-16 07:05:22 +000014671 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014672 for (const auto &E : Proto->exceptions()) {
14673 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014674 return true;
14675 }
14676 break;
14677 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014678
14679 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014680}
14681
14682bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14683 FindCXXThisExpr Finder(*this);
14684
14685 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014686 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014687 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014688 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014689 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014690 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014691 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014692 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014693 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014694 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014695 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014696 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014697 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014698 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014699 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014700 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014701 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014702 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014703 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014704 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014705 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014706 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014707 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014708 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014709 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014710 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014711 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014712 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014713 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014714 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014715 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014716
14717 if (Arg && !Finder.TraverseStmt(Arg))
14718 return true;
14719
14720 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14721 if (!Finder.TraverseStmt(Args[I]))
14722 return true;
14723 }
14724 }
14725
14726 return false;
14727}
14728
Richard Smith2e321552014-11-12 02:00:47 +000014729void Sema::checkExceptionSpecification(
14730 bool IsTopLevel, ExceptionSpecificationType EST,
14731 ArrayRef<ParsedType> DynamicExceptions,
14732 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14733 SmallVectorImpl<QualType> &Exceptions,
14734 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014735 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014736 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014737 if (EST == EST_Dynamic) {
14738 Exceptions.reserve(DynamicExceptions.size());
14739 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14740 // FIXME: Preserve type source info.
14741 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14742
Richard Smith2e321552014-11-12 02:00:47 +000014743 if (IsTopLevel) {
14744 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14745 collectUnexpandedParameterPacks(ET, Unexpanded);
14746 if (!Unexpanded.empty()) {
14747 DiagnoseUnexpandedParameterPacks(
14748 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14749 Unexpanded);
14750 continue;
14751 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014752 }
14753
14754 // Check that the type is valid for an exception spec, and
14755 // drop it if not.
14756 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14757 Exceptions.push_back(ET);
14758 }
Richard Smith8acb4282014-07-31 21:57:55 +000014759 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014760 return;
14761 }
Richard Smith8acb4282014-07-31 21:57:55 +000014762
Douglas Gregor433e0532012-04-16 18:27:27 +000014763 if (EST == EST_ComputedNoexcept) {
14764 // If an error occurred, there's no expression here.
14765 if (NoexceptExpr) {
14766 assert((NoexceptExpr->isTypeDependent() ||
14767 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14768 Context.BoolTy) &&
14769 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014770 if (IsTopLevel && NoexceptExpr &&
14771 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014772 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014773 return;
14774 }
Richard Smith8acb4282014-07-31 21:57:55 +000014775
Douglas Gregor433e0532012-04-16 18:27:27 +000014776 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014777 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014778 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014779 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014780 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014781 }
14782 return;
14783 }
14784}
14785
Richard Smith0b3a4622014-11-13 20:01:57 +000014786void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14787 ExceptionSpecificationType EST,
14788 SourceRange SpecificationRange,
14789 ArrayRef<ParsedType> DynamicExceptions,
14790 ArrayRef<SourceRange> DynamicExceptionRanges,
14791 Expr *NoexceptExpr) {
14792 if (!MethodD)
14793 return;
14794
14795 // Dig out the method we're referring to.
14796 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14797 MethodD = FunTmpl->getTemplatedDecl();
14798
14799 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14800 if (!Method)
14801 return;
14802
14803 // Check the exception specification.
14804 llvm::SmallVector<QualType, 4> Exceptions;
14805 FunctionProtoType::ExceptionSpecInfo ESI;
14806 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14807 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14808 ESI);
14809
14810 // Update the exception specification on the function type.
14811 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14812
14813 if (Method->isStatic())
14814 checkThisInStaticMemberFunctionExceptionSpec(Method);
14815
14816 if (Method->isVirtual()) {
14817 // Check overrides, which we previously had to delay.
14818 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14819 OEnd = Method->end_overridden_methods();
14820 O != OEnd; ++O)
14821 CheckOverridingFunctionExceptionSpec(Method, *O);
14822 }
14823}
14824
John McCall5e77d762013-04-16 07:28:30 +000014825/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14826///
14827MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14828 SourceLocation DeclStart,
14829 Declarator &D, Expr *BitWidth,
14830 InClassInitStyle InitStyle,
14831 AccessSpecifier AS,
14832 AttributeList *MSPropertyAttr) {
14833 IdentifierInfo *II = D.getIdentifier();
14834 if (!II) {
14835 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014836 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014837 }
14838 SourceLocation Loc = D.getIdentifierLoc();
14839
14840 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14841 QualType T = TInfo->getType();
14842 if (getLangOpts().CPlusPlus) {
14843 CheckExtraCXXDefaultArguments(D);
14844
14845 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14846 UPPC_DataMemberType)) {
14847 D.setInvalidType();
14848 T = Context.IntTy;
14849 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14850 }
14851 }
14852
14853 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14854
Richard Smith62f19e72016-06-25 00:15:56 +000014855 if (D.getDeclSpec().isInlineSpecified())
14856 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14857 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014858 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14859 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14860 diag::err_invalid_thread)
14861 << DeclSpec::getSpecifierName(TSCS);
14862
14863 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014864 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014865 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14866 LookupName(Previous, S);
14867 switch (Previous.getResultKind()) {
14868 case LookupResult::Found:
14869 case LookupResult::FoundUnresolvedValue:
14870 PrevDecl = Previous.getAsSingle<NamedDecl>();
14871 break;
14872
14873 case LookupResult::FoundOverloaded:
14874 PrevDecl = Previous.getRepresentativeDecl();
14875 break;
14876
14877 case LookupResult::NotFound:
14878 case LookupResult::NotFoundInCurrentInstantiation:
14879 case LookupResult::Ambiguous:
14880 break;
14881 }
14882
14883 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14884 // Maybe we will complain about the shadowed template parameter.
14885 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14886 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014887 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014888 }
14889
14890 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014891 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014892
14893 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014894 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014895 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14896 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014897 ProcessDeclAttributes(TUScope, NewPD, D);
14898 NewPD->setAccess(AS);
14899
14900 if (NewPD->isInvalidDecl())
14901 Record->setInvalidDecl();
14902
14903 if (D.getDeclSpec().isModulePrivateSpecified())
14904 NewPD->setModulePrivate();
14905
14906 if (NewPD->isInvalidDecl() && PrevDecl) {
14907 // Don't introduce NewFD into scope; there's already something
14908 // with the same name in the same scope.
14909 } else if (II) {
14910 PushOnScopeChains(NewPD, S);
14911 } else
14912 Record->addDecl(NewPD);
14913
14914 return NewPD;
14915}