blob: 06c6af1a1978b809fe6ac446dbbfd6d2308c465f [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 Parsonsff0382c2016-11-17 17:52:58 +0000398 std::unique_ptr<CachedTokens> Toks = std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
David Majnemerb3c6d522015-01-13 07:42:33 +0000399 SourceRange SR;
400 if (Toks->size() > 1)
401 SR = SourceRange((*Toks)[1].getLocation(),
402 Toks->back().getLocation());
403 else
404 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000406 << SR;
Douglas Gregor58354032008-12-24 00:01:03 +0000407 } else if (Param->getDefaultArg()) {
408 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
409 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000410 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000411 }
412 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000413 } else if (chunk.Kind != DeclaratorChunk::Paren) {
414 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000415 }
416 }
417}
418
David Majnemer502b0ed2013-06-25 23:09:30 +0000419static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
420 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
421 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
422 if (!PVD->hasDefaultArg())
423 return false;
424 if (!PVD->hasInheritedDefaultArg())
425 return true;
426 }
427 return false;
428}
429
Craig Toppere4794282012-09-21 04:33:26 +0000430/// MergeCXXFunctionDecl - Merge two declarations of the same C++
431/// function, once we already know that they have the same
432/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
433/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000434bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
435 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000436 bool Invalid = false;
437
Richard Smithc7d48d12015-05-20 17:50:35 +0000438 // The declaration context corresponding to the scope is the semantic
439 // parent, unless this is a local function declaration, in which case
440 // it is that surrounding function.
441 DeclContext *ScopeDC = New->isLocalExternDecl()
442 ? New->getLexicalDeclContext()
443 : New->getDeclContext();
444
445 // Find the previous declaration for the purpose of default arguments.
446 FunctionDecl *PrevForDefaultArgs = Old;
447 for (/**/; PrevForDefaultArgs;
448 // Don't bother looking back past the latest decl if this is a local
449 // extern declaration; nothing else could work.
450 PrevForDefaultArgs = New->isLocalExternDecl()
451 ? nullptr
452 : PrevForDefaultArgs->getPreviousDecl()) {
453 // Ignore hidden declarations.
454 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
455 continue;
456
457 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
458 !New->isCXXClassMember()) {
459 // Ignore default arguments of old decl if they are not in
460 // the same scope and this is not an out-of-line definition of
461 // a member function.
462 continue;
463 }
464
465 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
466 // If only one of these is a local function declaration, then they are
467 // declared in different scopes, even though isDeclInScope may think
468 // they're in the same scope. (If both are local, the scope check is
469 // sufficent, and if neither is local, then they are in the same scope.)
470 continue;
471 }
472
Nico Webera6916892016-06-10 18:53:04 +0000473 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000474 break;
475 }
476
Chris Lattner199abbc2008-04-08 05:04:30 +0000477 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // For non-template functions, default arguments can be added in
479 // later declarations of a function in the same
480 // scope. Declarations in different scopes have completely
481 // distinct sets of default arguments. That is, declarations in
482 // inner scopes do not acquire default arguments from
483 // declarations in outer scopes, and vice versa. In a given
484 // function declaration, all parameters subsequent to a
485 // parameter with a default argument shall have default
486 // arguments supplied in this or previous declarations. A
487 // default argument shall not be redefined by a later
488 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000489 //
490 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000491 // Except for member functions of class templates, the default arguments
492 // in a member function definition that appears outside of the class
493 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000494 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000495 for (unsigned p = 0, NumParams = PrevForDefaultArgs
496 ? PrevForDefaultArgs->getNumParams()
497 : 0;
498 p < NumParams; ++p) {
499 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000500 ParmVarDecl *NewParam = New->getParamDecl(p);
501
Richard Smithc7d48d12015-05-20 17:50:35 +0000502 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000503 bool NewParamHasDfl = NewParam->hasDefaultArg();
504
James Molloye9430032012-03-13 08:55:35 +0000505 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000506 unsigned DiagDefaultParamID =
507 diag::err_param_default_argument_redefinition;
508
509 // MSVC accepts that default parameters be redefined for member functions
510 // of template class. The new default parameter's value is ignored.
511 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000512 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000514 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000515 // Merge the old default argument into the new parameter.
516 NewParam->setHasInheritedDefaultArg();
517 if (OldParam->hasUninstantiatedDefaultArg())
518 NewParam->setUninstantiatedDefaultArg(
519 OldParam->getUninstantiatedDefaultArg());
520 else
521 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000522 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000523 Invalid = false;
524 }
525 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000526
Francois Pichet8cb243a2011-04-10 04:58:30 +0000527 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
528 // hint here. Alternatively, we could walk the type-source information
529 // for NewParam to find the last source location in the type... but it
530 // isn't worth the effort right now. This is the kind of test case that
531 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000532 // int f(int);
533 // void g(int (*fp)(int) = f);
534 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000535 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000536 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000537
538 // Look for the function declaration where the default argument was
539 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000540 for (auto Older = PrevForDefaultArgs;
541 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000542 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000543 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000544 }
545
Douglas Gregorc732aba2009-09-11 18:44:32 +0000546 Diag(OldParam->getLocation(), diag::note_previous_definition)
547 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000548 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000549 // Merge the old default argument into the new parameter.
550 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000551 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000552 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000553 if (OldParam->hasUnparsedDefaultArg())
554 NewParam->setUnparsedDefaultArg();
555 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000556 NewParam->setUninstantiatedDefaultArg(
557 OldParam->getUninstantiatedDefaultArg());
558 else
John McCalle61b02b2010-05-04 01:53:42 +0000559 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000560 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000561 if (New->getDescribedFunctionTemplate()) {
562 // Paragraph 4, quoted above, only applies to non-template functions.
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_template_redecl)
565 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000566 Diag(PrevForDefaultArgs->getLocation(),
567 diag::note_template_prev_declaration)
568 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000569 } else if (New->getTemplateSpecializationKind()
570 != TSK_ImplicitInstantiation &&
571 New->getTemplateSpecializationKind() != TSK_Undeclared) {
572 // C++ [temp.expr.spec]p21:
573 // Default function arguments shall not be specified in a declaration
574 // or a definition for one of the following explicit specializations:
575 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000576 // - the explicit specialization of a member function template;
577 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000578 // template where the class template specialization to which the
579 // member function specialization belongs is implicitly
580 // instantiated.
581 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
582 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
583 << New->getDeclName()
584 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000585 } else if (New->getDeclContext()->isDependentContext()) {
586 // C++ [dcl.fct.default]p6 (DR217):
587 // Default arguments for a member function of a class template shall
588 // be specified on the initial declaration of the member function
589 // within the class template.
590 //
591 // Reading the tea leaves a bit in DR217 and its reference to DR205
592 // leads me to the conclusion that one cannot add default function
593 // arguments for an out-of-line definition of a member function of a
594 // dependent type.
595 int WhichKind = 2;
596 if (CXXRecordDecl *Record
597 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
598 if (Record->getDescribedClassTemplate())
599 WhichKind = 0;
600 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
601 WhichKind = 1;
602 else
603 WhichKind = 2;
604 }
605
606 Diag(NewParam->getLocation(),
607 diag::err_param_default_argument_member_template_redecl)
608 << WhichKind
609 << NewParam->getDefaultArgRange();
610 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000611 }
612 }
613
Richard Smith58c3cc12012-11-28 03:45:24 +0000614 // DR1344: If a default argument is added outside a class definition and that
615 // default argument makes the function a special member function, the program
616 // is ill-formed. This can only happen for constructors.
617 if (isa<CXXConstructorDecl>(New) &&
618 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
619 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
620 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
621 if (NewSM != OldSM) {
622 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
623 assert(NewParam->hasDefaultArg());
624 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
625 << NewParam->getDefaultArgRange() << NewSM;
626 Diag(Old->getLocation(), diag::note_previous_declaration);
627 }
628 }
629
David Majnemeree4f4022014-03-30 06:44:54 +0000630 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000631 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000632 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000633 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000634 if (New->isConstexpr() != Old->isConstexpr()) {
635 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
636 << New << New->isConstexpr();
637 Diag(Old->getLocation(), diag::note_previous_declaration);
638 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000639 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
640 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000641 // C++11 [dcl.fcn.spec]p4:
642 // If the definition of a function appears in a translation unit before its
643 // first declaration as inline, the program is ill-formed.
644 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
645 Diag(Def->getLocation(), diag::note_previous_definition);
646 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000647 }
648
David Majnemer502b0ed2013-06-25 23:09:30 +0000649 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000650 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000651 // the only declaration of the function or function template in the
652 // translation unit.
653 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
654 functionDeclHasDefaultArgument(Old)) {
655 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
656 Diag(Old->getLocation(), diag::note_previous_declaration);
657 Invalid = true;
658 }
659
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000660 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000661}
662
Richard Smith7873de02016-08-11 22:25:46 +0000663NamedDecl *
664Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
665 MultiTemplateParamsArg TemplateParamLists) {
666 assert(D.isDecompositionDeclarator());
667 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
668
669 // The syntax only allows a decomposition declarator as a simple-declaration
670 // or a for-range-declaration, but we parse it in more cases than that.
671 if (!D.mayHaveDecompositionDeclarator()) {
672 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
673 << Decomp.getSourceRange();
674 return nullptr;
675 }
676
677 if (!TemplateParamLists.empty()) {
678 // FIXME: There's no rule against this, but there are also no rules that
679 // would actually make it usable, so we reject it for now.
680 Diag(TemplateParamLists.front()->getTemplateLoc(),
681 diag::err_decomp_decl_template);
682 return nullptr;
683 }
684
685 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
686 ? diag::warn_cxx14_compat_decomp_decl
687 : diag::ext_decomp_decl)
688 << Decomp.getSourceRange();
689
690 // The semantic context is always just the current context.
691 DeclContext *const DC = CurContext;
692
693 // C++1z [dcl.dcl]/8:
694 // The decl-specifier-seq shall contain only the type-specifier auto
695 // and cv-qualifiers.
696 auto &DS = D.getDeclSpec();
697 {
698 SmallVector<StringRef, 8> BadSpecifiers;
699 SmallVector<SourceLocation, 8> BadSpecifierLocs;
700 if (auto SCS = DS.getStorageClassSpec()) {
701 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
702 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
703 }
704 if (auto TSCS = DS.getThreadStorageClassSpec()) {
705 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
706 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
707 }
708 if (DS.isConstexprSpecified()) {
709 BadSpecifiers.push_back("constexpr");
710 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
711 }
712 if (DS.isInlineSpecified()) {
713 BadSpecifiers.push_back("inline");
714 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
715 }
716 if (!BadSpecifiers.empty()) {
717 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
718 Err << (int)BadSpecifiers.size()
719 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
720 // Don't add FixItHints to remove the specifiers; we do still respect
721 // them when building the underlying variable.
722 for (auto Loc : BadSpecifierLocs)
723 Err << SourceRange(Loc, Loc);
724 }
725 // We can't recover from it being declared as a typedef.
726 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
727 return nullptr;
728 }
729
730 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
731 QualType R = TInfo->getType();
732
733 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
734 UPPC_DeclarationType))
735 D.setInvalidType();
736
737 // The syntax only allows a single ref-qualifier prior to the decomposition
738 // declarator. No other declarator chunks are permitted. Also check the type
739 // specifier here.
740 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
741 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
742 (D.getNumTypeObjects() == 1 &&
743 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
744 Diag(Decomp.getLSquareLoc(),
745 (D.hasGroupingParens() ||
746 (D.getNumTypeObjects() &&
747 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
748 ? diag::err_decomp_decl_parens
749 : diag::err_decomp_decl_type)
750 << R;
751
752 // In most cases, there's no actual problem with an explicitly-specified
753 // type, but a function type won't work here, and ActOnVariableDeclarator
754 // shouldn't be called for such a type.
755 if (R->isFunctionType())
756 D.setInvalidType();
757 }
758
759 // Build the BindingDecls.
760 SmallVector<BindingDecl*, 8> Bindings;
761
762 // Build the BindingDecls.
763 for (auto &B : D.getDecompositionDeclarator().bindings()) {
764 // Check for name conflicts.
765 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
767 ForRedeclaration);
768 LookupName(Previous, S,
769 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
770
771 // It's not permitted to shadow a template parameter name.
772 if (Previous.isSingleResult() &&
773 Previous.getFoundDecl()->isTemplateParameter()) {
774 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
775 Previous.getFoundDecl());
776 Previous.clear();
777 }
778
779 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
780 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
781 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
782 /*AllowInlineNamespace*/false);
783 if (!Previous.empty()) {
784 auto *Old = Previous.getRepresentativeDecl();
785 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
786 Diag(Old->getLocation(), diag::note_previous_definition);
787 }
788
Richard Smith32cb8c92016-08-12 00:53:41 +0000789 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000790 PushOnScopeChains(BD, S, true);
791 Bindings.push_back(BD);
792 ParsingInitForAutoVars.insert(BD);
793 }
794
795 // There are no prior lookup results for the variable itself, because it
796 // is unnamed.
797 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
798 Decomp.getLSquareLoc());
799 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
800
801 // Build the variable that holds the non-decomposed object.
802 bool AddToScope = true;
803 NamedDecl *New =
804 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
805 MultiTemplateParamsArg(), AddToScope, Bindings);
806 CurContext->addHiddenDecl(New);
807
808 if (isInOpenMPDeclareTargetContext())
809 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
810
811 return New;
812}
813
814static bool checkSimpleDecomposition(
815 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
816 QualType DecompType, llvm::APSInt NumElems, QualType ElemType,
817 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
818 if ((int64_t)Bindings.size() != NumElems) {
819 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
820 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
821 << (NumElems < Bindings.size());
822 return true;
823 }
824
825 unsigned I = 0;
826 for (auto *B : Bindings) {
827 SourceLocation Loc = B->getLocation();
828 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
829 if (E.isInvalid())
830 return true;
831 E = GetInit(Loc, E.get(), I++);
832 if (E.isInvalid())
833 return true;
834 B->setBinding(ElemType, E.get());
835 }
836
837 return false;
838}
839
840static bool checkArrayLikeDecomposition(Sema &S,
841 ArrayRef<BindingDecl *> Bindings,
842 ValueDecl *Src, QualType DecompType,
843 llvm::APSInt NumElems,
844 QualType ElemType) {
845 return checkSimpleDecomposition(
846 S, Bindings, Src, DecompType, NumElems, ElemType,
847 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
848 ExprResult E = S.ActOnIntegerConstant(Loc, I);
849 if (E.isInvalid())
850 return ExprError();
851 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
852 });
853}
854
855static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
856 ValueDecl *Src, QualType DecompType,
857 const ConstantArrayType *CAT) {
858 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
859 llvm::APSInt(CAT->getSize()),
860 CAT->getElementType());
861}
862
863static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
864 ValueDecl *Src, QualType DecompType,
865 const VectorType *VT) {
866 return checkArrayLikeDecomposition(
867 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
868 S.Context.getQualifiedType(VT->getElementType(),
869 DecompType.getQualifiers()));
870}
871
872static bool checkComplexDecomposition(Sema &S,
873 ArrayRef<BindingDecl *> Bindings,
874 ValueDecl *Src, QualType DecompType,
875 const ComplexType *CT) {
876 return checkSimpleDecomposition(
877 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
878 S.Context.getQualifiedType(CT->getElementType(),
879 DecompType.getQualifiers()),
880 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
881 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
882 });
883}
884
885static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
886 TemplateArgumentListInfo &Args) {
887 SmallString<128> SS;
888 llvm::raw_svector_ostream OS(SS);
889 bool First = true;
890 for (auto &Arg : Args.arguments()) {
891 if (!First)
892 OS << ", ";
893 Arg.getArgument().print(PrintingPolicy, OS);
894 First = false;
895 }
896 return OS.str();
897}
898
899static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
900 SourceLocation Loc, StringRef Trait,
901 TemplateArgumentListInfo &Args,
902 unsigned DiagID) {
903 auto DiagnoseMissing = [&] {
904 if (DiagID)
905 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
906 Args);
907 return true;
908 };
909
910 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
911 NamespaceDecl *Std = S.getStdNamespace();
912 if (!Std)
913 return DiagnoseMissing();
914
915 // Look up the trait itself, within namespace std. We can diagnose various
916 // problems with this lookup even if we've been asked to not diagnose a
917 // missing specialization, because this can only fail if the user has been
918 // declaring their own names in namespace std or we don't support the
919 // standard library implementation in use.
920 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
921 Loc, Sema::LookupOrdinaryName);
922 if (!S.LookupQualifiedName(Result, Std))
923 return DiagnoseMissing();
924 if (Result.isAmbiguous())
925 return true;
926
927 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
928 if (!TraitTD) {
929 Result.suppressDiagnostics();
930 NamedDecl *Found = *Result.begin();
931 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
932 S.Diag(Found->getLocation(), diag::note_declared_at);
933 return true;
934 }
935
936 // Build the template-id.
937 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
938 if (TraitTy.isNull())
939 return true;
940 if (!S.isCompleteType(Loc, TraitTy)) {
941 if (DiagID)
942 S.RequireCompleteType(
943 Loc, TraitTy, DiagID,
944 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
945 return true;
946 }
947
948 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
949 assert(RD && "specialization of class template is not a class?");
950
951 // Look up the member of the trait type.
952 S.LookupQualifiedName(TraitMemberLookup, RD);
953 return TraitMemberLookup.isAmbiguous();
954}
955
956static TemplateArgumentLoc
957getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
958 uint64_t I) {
959 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
960 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
961}
962
963static TemplateArgumentLoc
964getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
965 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
966}
967
968namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
969
970static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
971 llvm::APSInt &Size) {
972 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
973
974 DeclarationName Value = S.PP.getIdentifierInfo("value");
975 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
976
977 // Form template argument list for tuple_size<T>.
978 TemplateArgumentListInfo Args(Loc, Loc);
979 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
980
981 // If there's no tuple_size specialization, it's not tuple-like.
982 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
983 return IsTupleLike::NotTupleLike;
984
985 // FIXME: According to the standard, we're not supposed to diagnose if any
986 // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
987 // results in an error), but this is subject to a pending CWG issue / NB
988 // comment, which says we do diagnose if tuple_size<T> is complete but
989 // tuple_size<T>::value is not an ICE.
990
991 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
992 LookupResult &R;
993 TemplateArgumentListInfo &Args;
994 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
995 : R(R), Args(Args) {}
996 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
997 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
998 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
999 }
1000 } Diagnoser(R, Args);
1001
1002 if (R.empty()) {
1003 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1004 return IsTupleLike::Error;
1005 }
1006
1007 ExprResult E =
1008 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1009 if (E.isInvalid())
1010 return IsTupleLike::Error;
1011
1012 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1013 if (E.isInvalid())
1014 return IsTupleLike::Error;
1015
1016 return IsTupleLike::TupleLike;
1017}
1018
1019/// \return std::tuple_element<I, T>::type.
1020static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1021 unsigned I, QualType T) {
1022 // Form template argument list for tuple_element<I, T>.
1023 TemplateArgumentListInfo Args(Loc, Loc);
1024 Args.addArgument(
1025 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1026 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1027
1028 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1029 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1030 if (lookupStdTypeTraitMember(
1031 S, R, Loc, "tuple_element", Args,
1032 diag::err_decomp_decl_std_tuple_element_not_specialized))
1033 return QualType();
1034
1035 auto *TD = R.getAsSingle<TypeDecl>();
1036 if (!TD) {
1037 R.suppressDiagnostics();
1038 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1039 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1040 if (!R.empty())
1041 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1042 return QualType();
1043 }
1044
1045 return S.Context.getTypeDeclType(TD);
1046}
1047
1048namespace {
1049struct BindingDiagnosticTrap {
1050 Sema &S;
1051 DiagnosticErrorTrap Trap;
1052 BindingDecl *BD;
1053
1054 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1055 : S(S), Trap(S.Diags), BD(BD) {}
1056 ~BindingDiagnosticTrap() {
1057 if (Trap.hasErrorOccurred())
1058 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1059 }
1060};
1061}
1062
Richard Smith3997b1b2016-08-12 01:55:21 +00001063static bool checkTupleLikeDecomposition(Sema &S,
1064 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001065 VarDecl *Src, QualType DecompType,
Richard Smith3997b1b2016-08-12 01:55:21 +00001066 llvm::APSInt TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001067 if ((int64_t)Bindings.size() != TupleSize) {
1068 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1069 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1070 << (TupleSize < Bindings.size());
1071 return true;
1072 }
1073
1074 if (Bindings.empty())
1075 return false;
1076
1077 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1078
1079 // [dcl.decomp]p3:
1080 // The unqualified-id get is looked up in the scope of E by class member
1081 // access lookup
1082 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1083 bool UseMemberGet = false;
1084 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1085 if (auto *RD = DecompType->getAsCXXRecordDecl())
1086 S.LookupQualifiedName(MemberGet, RD);
1087 if (MemberGet.isAmbiguous())
1088 return true;
1089 UseMemberGet = !MemberGet.empty();
1090 S.FilterAcceptableTemplateNames(MemberGet);
1091 }
1092
1093 unsigned I = 0;
1094 for (auto *B : Bindings) {
1095 BindingDiagnosticTrap Trap(S, B);
1096 SourceLocation Loc = B->getLocation();
1097
1098 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1099 if (E.isInvalid())
1100 return true;
1101
1102 // e is an lvalue if the type of the entity is an lvalue reference and
1103 // an xvalue otherwise
1104 if (!Src->getType()->isLValueReferenceType())
1105 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1106 E.get(), nullptr, VK_XValue);
1107
1108 TemplateArgumentListInfo Args(Loc, Loc);
1109 Args.addArgument(
1110 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1111
1112 if (UseMemberGet) {
1113 // if [lookup of member get] finds at least one declaration, the
1114 // initializer is e.get<i-1>().
1115 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1116 CXXScopeSpec(), SourceLocation(), nullptr,
1117 MemberGet, &Args, nullptr);
1118 if (E.isInvalid())
1119 return true;
1120
1121 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1122 } else {
1123 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1124 // in the associated namespaces.
1125 Expr *Get = UnresolvedLookupExpr::Create(
1126 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1127 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1128 UnresolvedSetIterator(), UnresolvedSetIterator());
1129
1130 Expr *Arg = E.get();
1131 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1132 }
1133 if (E.isInvalid())
1134 return true;
1135 Expr *Init = E.get();
1136
1137 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1138 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1139 if (T.isNull())
1140 return true;
1141
1142 // each vi is a variable of type "reference to T" initialized with the
1143 // initializer, where the reference is an lvalue reference if the
1144 // initializer is an lvalue and an rvalue reference otherwise
1145 QualType RefType =
1146 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1147 if (RefType.isNull())
1148 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001149 auto *RefVD = VarDecl::Create(
1150 S.Context, Src->getDeclContext(), Loc, Loc,
1151 B->getDeclName().getAsIdentifierInfo(), RefType,
1152 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1153 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1154 RefVD->setTSCSpec(Src->getTSCSpec());
1155 RefVD->setImplicit();
1156 if (Src->isInlineSpecified())
1157 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001158 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001159
Richard Smith97fcf4b2016-08-14 23:15:52 +00001160 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001161 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1162 InitializationSequence Seq(S, Entity, Kind, Init);
1163 E = Seq.Perform(S, Entity, Kind, Init);
1164 if (E.isInvalid())
1165 return true;
Richard Smithda383632016-08-15 01:33:41 +00001166 E = S.ActOnFinishFullExpr(E.get(), Loc);
1167 if (E.isInvalid())
1168 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001169 RefVD->setInit(E.get());
1170 RefVD->checkInitIsICE();
1171
Richard Smith97fcf4b2016-08-14 23:15:52 +00001172 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1173 DeclarationNameInfo(B->getDeclName(), Loc),
1174 RefVD);
1175 if (E.isInvalid())
1176 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001177
1178 B->setBinding(T, E.get());
1179 I++;
1180 }
1181
1182 return false;
1183}
1184
1185/// Find the base class to decompose in a built-in decomposition of a class type.
1186/// This base class search is, unfortunately, not quite like any other that we
1187/// perform anywhere else in C++.
1188static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1189 SourceLocation Loc,
1190 const CXXRecordDecl *RD,
1191 CXXCastPath &BasePath) {
1192 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1193 CXXBasePath &Path) {
1194 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1195 };
1196
1197 const CXXRecordDecl *ClassWithFields = nullptr;
1198 if (RD->hasDirectFields())
1199 // [dcl.decomp]p4:
1200 // Otherwise, all of E's non-static data members shall be public direct
1201 // members of E ...
1202 ClassWithFields = RD;
1203 else {
1204 // ... or of ...
1205 CXXBasePaths Paths;
1206 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1207 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1208 // If no classes have fields, just decompose RD itself. (This will work
1209 // if and only if zero bindings were provided.)
1210 return RD;
1211 }
1212
1213 CXXBasePath *BestPath = nullptr;
1214 for (auto &P : Paths) {
1215 if (!BestPath)
1216 BestPath = &P;
1217 else if (!S.Context.hasSameType(P.back().Base->getType(),
1218 BestPath->back().Base->getType())) {
1219 // ... the same ...
1220 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1221 << false << RD << BestPath->back().Base->getType()
1222 << P.back().Base->getType();
1223 return nullptr;
1224 } else if (P.Access < BestPath->Access) {
1225 BestPath = &P;
1226 }
1227 }
1228
1229 // ... unambiguous ...
1230 QualType BaseType = BestPath->back().Base->getType();
1231 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1232 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1233 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1234 return nullptr;
1235 }
1236
1237 // ... public base class of E.
1238 if (BestPath->Access != AS_public) {
1239 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1240 << RD << BaseType;
1241 for (auto &BS : *BestPath) {
1242 if (BS.Base->getAccessSpecifier() != AS_public) {
1243 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1244 << (BS.Base->getAccessSpecifier() == AS_protected)
1245 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1246 break;
1247 }
1248 }
1249 return nullptr;
1250 }
1251
1252 ClassWithFields = BaseType->getAsCXXRecordDecl();
1253 S.BuildBasePathArray(Paths, BasePath);
1254 }
1255
1256 // The above search did not check whether the selected class itself has base
1257 // classes with fields, so check that now.
1258 CXXBasePaths Paths;
1259 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1260 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1261 << (ClassWithFields == RD) << RD << ClassWithFields
1262 << Paths.front().back().Base->getType();
1263 return nullptr;
1264 }
1265
1266 return ClassWithFields;
1267}
1268
1269static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1270 ValueDecl *Src, QualType DecompType,
1271 const CXXRecordDecl *RD) {
1272 CXXCastPath BasePath;
1273 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1274 if (!RD)
1275 return true;
1276 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1277 DecompType.getQualifiers());
1278
1279 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001280 unsigned NumFields =
1281 std::count_if(RD->field_begin(), RD->field_end(),
1282 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001283 assert(Bindings.size() != NumFields);
1284 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1285 << DecompType << (unsigned)Bindings.size() << NumFields
1286 << (NumFields < Bindings.size());
1287 return true;
1288 };
1289
1290 // all of E's non-static data members shall be public [...] members,
1291 // E shall not have an anonymous union member, ...
1292 unsigned I = 0;
1293 for (auto *FD : RD->fields()) {
1294 if (FD->isUnnamedBitfield())
1295 continue;
1296
1297 if (FD->isAnonymousStructOrUnion()) {
1298 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1299 << DecompType << FD->getType()->isUnionType();
1300 S.Diag(FD->getLocation(), diag::note_declared_at);
1301 return true;
1302 }
1303
1304 // We have a real field to bind.
1305 if (I >= Bindings.size())
1306 return DiagnoseBadNumberOfBindings();
1307 auto *B = Bindings[I++];
1308
1309 SourceLocation Loc = B->getLocation();
1310 if (FD->getAccess() != AS_public) {
1311 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1312
1313 // Determine whether the access specifier was explicit.
1314 bool Implicit = true;
1315 for (const auto *D : RD->decls()) {
1316 if (declaresSameEntity(D, FD))
1317 break;
1318 if (isa<AccessSpecDecl>(D)) {
1319 Implicit = false;
1320 break;
1321 }
1322 }
1323
1324 S.Diag(FD->getLocation(), diag::note_access_natural)
1325 << (FD->getAccess() == AS_protected) << Implicit;
1326 return true;
1327 }
1328
1329 // Initialize the binding to Src.FD.
1330 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1331 if (E.isInvalid())
1332 return true;
1333 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1334 VK_LValue, &BasePath);
1335 if (E.isInvalid())
1336 return true;
1337 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1338 CXXScopeSpec(), FD,
1339 DeclAccessPair::make(FD, FD->getAccess()),
1340 DeclarationNameInfo(FD->getDeclName(), Loc));
1341 if (E.isInvalid())
1342 return true;
1343
1344 // If the type of the member is T, the referenced type is cv T, where cv is
1345 // the cv-qualification of the decomposition expression.
1346 //
1347 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1348 // 'const' to the type of the field.
1349 Qualifiers Q = DecompType.getQualifiers();
1350 if (FD->isMutable())
1351 Q.removeConst();
1352 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1353 }
1354
1355 if (I != Bindings.size())
1356 return DiagnoseBadNumberOfBindings();
1357
1358 return false;
1359}
1360
Richard Smith3997b1b2016-08-12 01:55:21 +00001361void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001362 QualType DecompType = DD->getType();
1363
1364 // If the type of the decomposition is dependent, then so is the type of
1365 // each binding.
1366 if (DecompType->isDependentType()) {
1367 for (auto *B : DD->bindings())
1368 B->setType(Context.DependentTy);
1369 return;
1370 }
1371
1372 DecompType = DecompType.getNonReferenceType();
1373 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1374
1375 // C++1z [dcl.decomp]/2:
1376 // If E is an array type [...]
1377 // As an extension, we also support decomposition of built-in complex and
1378 // vector types.
1379 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1380 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1381 DD->setInvalidDecl();
1382 return;
1383 }
1384 if (auto *VT = DecompType->getAs<VectorType>()) {
1385 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1386 DD->setInvalidDecl();
1387 return;
1388 }
1389 if (auto *CT = DecompType->getAs<ComplexType>()) {
1390 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1391 DD->setInvalidDecl();
1392 return;
1393 }
1394
1395 // C++1z [dcl.decomp]/3:
1396 // if the expression std::tuple_size<E>::value is a well-formed integral
1397 // constant expression, [...]
1398 llvm::APSInt TupleSize(32);
1399 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1400 case IsTupleLike::Error:
1401 DD->setInvalidDecl();
1402 return;
1403
1404 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001405 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001406 DD->setInvalidDecl();
1407 return;
1408
1409 case IsTupleLike::NotTupleLike:
1410 break;
1411 }
1412
1413 // C++1z [dcl.dcl]/8:
1414 // [E shall be of array or non-union class type]
1415 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1416 if (!RD || RD->isUnion()) {
1417 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1418 << DD << !RD << DecompType;
1419 DD->setInvalidDecl();
1420 return;
1421 }
1422
1423 // C++1z [dcl.decomp]/4:
1424 // all of E's non-static data members shall be [...] direct members of
1425 // E or of the same unambiguous public base class of E, ...
1426 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1427 DD->setInvalidDecl();
1428}
1429
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001430/// \brief Merge the exception specifications of two variable declarations.
1431///
1432/// This is called when there's a redeclaration of a VarDecl. The function
1433/// checks if the redeclaration might have an exception specification and
1434/// validates compatibility and merges the specs if necessary.
1435void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1436 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001437 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001438 return;
1439
1440 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1441 "Should only be called if types are otherwise the same.");
1442
1443 QualType NewType = New->getType();
1444 QualType OldType = Old->getType();
1445
1446 // We're only interested in pointers and references to functions, as well
1447 // as pointers to member functions.
1448 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1449 NewType = R->getPointeeType();
1450 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1451 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1452 NewType = P->getPointeeType();
1453 OldType = OldType->getAs<PointerType>()->getPointeeType();
1454 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1455 NewType = M->getPointeeType();
1456 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1457 }
1458
1459 if (!NewType->isFunctionProtoType())
1460 return;
1461
1462 // There's lots of special cases for functions. For function pointers, system
1463 // libraries are hopefully not as broken so that we don't need these
1464 // workarounds.
1465 if (CheckEquivalentExceptionSpec(
1466 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1467 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1468 New->setInvalidDecl();
1469 }
1470}
1471
Chris Lattner199abbc2008-04-08 05:04:30 +00001472/// CheckCXXDefaultArguments - Verify that the default arguments for a
1473/// function declaration are well-formed according to C++
1474/// [dcl.fct.default].
1475void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1476 unsigned NumParams = FD->getNumParams();
1477 unsigned p;
1478
1479 // Find first parameter with a default argument
1480 for (p = 0; p < NumParams; ++p) {
1481 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001482 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001483 break;
1484 }
1485
Benjamin Kramerfe257592015-03-27 13:58:41 +00001486 // C++11 [dcl.fct.default]p4:
1487 // In a given function declaration, each parameter subsequent to a parameter
1488 // with a default argument shall have a default argument supplied in this or
1489 // a previous declaration or shall be a function parameter pack. A default
1490 // argument shall not be redefined by a later declaration (not even to the
1491 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001492 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001493 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001494 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001495 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001496 if (Param->isInvalidDecl())
1497 /* We already complained about this parameter. */;
1498 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001499 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001500 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001501 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001502 else
Mike Stump11289f42009-09-09 15:08:12 +00001503 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001504 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001505
Chris Lattner199abbc2008-04-08 05:04:30 +00001506 LastMissingDefaultArg = p;
1507 }
1508 }
1509
1510 if (LastMissingDefaultArg > 0) {
1511 // Some default arguments were missing. Clear out all of the
1512 // default arguments up to (and including) the last missing
1513 // default argument, so that we leave the function parameters
1514 // in a semantically valid state.
1515 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1516 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001517 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001519 }
1520 }
1521 }
1522}
Douglas Gregor556877c2008-04-13 21:30:24 +00001523
Richard Smitheb3c10c2011-10-01 02:31:28 +00001524// CheckConstexprParameterTypes - Check whether a function's parameter types
1525// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001526// diagnostic and return false.
1527static bool CheckConstexprParameterTypes(Sema &SemaRef,
1528 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001529 unsigned ArgIndex = 0;
1530 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001531 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1532 e = FT->param_type_end();
1533 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001534 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1535 SourceLocation ParamLoc = PD->getLocation();
1536 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001537 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001538 diag::err_constexpr_non_literal_param,
1539 ArgIndex+1, PD->getSourceRange(),
1540 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001541 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001542 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001543 return true;
1544}
1545
1546/// \brief Get diagnostic %select index for tag kind for
1547/// record diagnostic message.
1548/// WARNING: Indexes apply to particular diagnostics only!
1549///
1550/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001551static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001552 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001553 case TTK_Struct: return 0;
1554 case TTK_Interface: return 1;
1555 case TTK_Class: return 2;
1556 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001557 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001558}
1559
1560// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1561// the requirements of a constexpr function definition or a constexpr
1562// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001563// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001564//
Richard Smith3607ffe2012-02-13 03:54:03 +00001565// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1566bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001567 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1568 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001569 // C++11 [dcl.constexpr]p4:
1570 // The definition of a constexpr constructor shall satisfy the following
1571 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001572 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001573 const CXXRecordDecl *RD = MD->getParent();
1574 if (RD->getNumVBases()) {
1575 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1576 << isa<CXXConstructorDecl>(NewFD)
1577 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001578 for (const auto &I : RD->vbases())
1579 Diag(I.getLocStart(),
1580 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001581 return false;
1582 }
Richard Smith7971b692012-01-13 04:54:00 +00001583 }
1584
1585 if (!isa<CXXConstructorDecl>(NewFD)) {
1586 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001587 // The definition of a constexpr function shall satisfy the following
1588 // constraints:
1589 // - it shall not be virtual;
1590 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1591 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001592 Method = Method->getCanonicalDecl();
1593 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001594
Richard Smith3607ffe2012-02-13 03:54:03 +00001595 // If it's not obvious why this function is virtual, find an overridden
1596 // function which uses the 'virtual' keyword.
1597 const CXXMethodDecl *WrittenVirtual = Method;
1598 while (!WrittenVirtual->isVirtualAsWritten())
1599 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1600 if (WrittenVirtual != Method)
1601 Diag(WrittenVirtual->getLocation(),
1602 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001603 return false;
1604 }
1605
1606 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001607 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001608 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001609 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001610 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001611 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001612 }
1613
Richard Smith7971b692012-01-13 04:54:00 +00001614 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001615 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001616 return false;
1617
Richard Smitheb3c10c2011-10-01 02:31:28 +00001618 return true;
1619}
1620
1621/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001622/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001623///
Richard Smithd9f663b2013-04-22 15:31:51 +00001624/// \return true if the body is OK (maybe only as an extension), false if we
1625/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001626static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001627 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1628 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001629 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1630 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001631 for (const auto *DclIt : DS->decls()) {
1632 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001633 case Decl::StaticAssert:
1634 case Decl::Using:
1635 case Decl::UsingShadow:
1636 case Decl::UsingDirective:
1637 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001638 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001639 // - static_assert-declarations
1640 // - using-declarations,
1641 // - using-directives,
1642 continue;
1643
1644 case Decl::Typedef:
1645 case Decl::TypeAlias: {
1646 // - typedef declarations and alias-declarations that do not define
1647 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001648 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001649 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1650 // Don't allow variably-modified types in constexpr functions.
1651 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1652 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1653 << TL.getSourceRange() << TL.getType()
1654 << isa<CXXConstructorDecl>(Dcl);
1655 return false;
1656 }
1657 continue;
1658 }
1659
1660 case Decl::Enum:
1661 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001662 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001663 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001664 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001665 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001666 ? diag::warn_cxx11_compat_constexpr_type_definition
1667 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001668 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001669 continue;
1670
Richard Smithd9f663b2013-04-22 15:31:51 +00001671 case Decl::EnumConstant:
1672 case Decl::IndirectField:
1673 case Decl::ParmVar:
1674 // These can only appear with other declarations which are banned in
1675 // C++11 and permitted in C++1y, so ignore them.
1676 continue;
1677
Richard Smithdca60b42016-08-12 00:39:32 +00001678 case Decl::Var:
1679 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001680 // C++1y [dcl.constexpr]p3 allows anything except:
1681 // a definition of a variable of non-literal type or of static or
1682 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001683 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001684 if (VD->isThisDeclarationADefinition()) {
1685 if (VD->isStaticLocal()) {
1686 SemaRef.Diag(VD->getLocation(),
1687 diag::err_constexpr_local_var_static)
1688 << isa<CXXConstructorDecl>(Dcl)
1689 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1690 return false;
1691 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001692 if (!VD->getType()->isDependentType() &&
1693 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001694 VD->getLocation(), VD->getType(),
1695 diag::err_constexpr_local_var_non_literal_type,
1696 isa<CXXConstructorDecl>(Dcl)))
1697 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001698 if (!VD->getType()->isDependentType() &&
1699 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001700 SemaRef.Diag(VD->getLocation(),
1701 diag::err_constexpr_local_var_no_init)
1702 << isa<CXXConstructorDecl>(Dcl);
1703 return false;
1704 }
1705 }
1706 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001707 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001708 ? diag::warn_cxx11_compat_constexpr_local_var
1709 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001710 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001711 continue;
1712 }
1713
1714 case Decl::NamespaceAlias:
1715 case Decl::Function:
1716 // These are disallowed in C++11 and permitted in C++1y. Allow them
1717 // everywhere as an extension.
1718 if (!Cxx1yLoc.isValid())
1719 Cxx1yLoc = DS->getLocStart();
1720 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001721
1722 default:
1723 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1724 << isa<CXXConstructorDecl>(Dcl);
1725 return false;
1726 }
1727 }
1728
1729 return true;
1730}
1731
1732/// Check that the given field is initialized within a constexpr constructor.
1733///
1734/// \param Dcl The constexpr constructor being checked.
1735/// \param Field The field being checked. This may be a member of an anonymous
1736/// struct or union nested within the class being checked.
1737/// \param Inits All declarations, including anonymous struct/union members and
1738/// indirect members, for which any initialization was provided.
1739/// \param Diagnosed Set to true if an error is produced.
1740static void CheckConstexprCtorInitializer(Sema &SemaRef,
1741 const FunctionDecl *Dcl,
1742 FieldDecl *Field,
1743 llvm::SmallSet<Decl*, 16> &Inits,
1744 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001745 if (Field->isInvalidDecl())
1746 return;
1747
Douglas Gregor556e5862011-10-10 17:22:13 +00001748 if (Field->isUnnamedBitfield())
1749 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001750
Richard Smithab44d5b2013-12-10 08:25:00 +00001751 // Anonymous unions with no variant members and empty anonymous structs do not
1752 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1753 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001754 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001755 (Field->getType()->isUnionType()
1756 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1757 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001758 return;
1759
Richard Smitheb3c10c2011-10-01 02:31:28 +00001760 if (!Inits.count(Field)) {
1761 if (!Diagnosed) {
1762 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1763 Diagnosed = true;
1764 }
1765 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1766 } else if (Field->isAnonymousStructOrUnion()) {
1767 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001768 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001769 // If an anonymous union contains an anonymous struct of which any member
1770 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001771 if (!RD->isUnion() || Inits.count(I))
1772 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001773 }
1774}
1775
Richard Smithd9f663b2013-04-22 15:31:51 +00001776/// Check the provided statement is allowed in a constexpr function
1777/// definition.
1778static bool
1779CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001780 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001781 SourceLocation &Cxx1yLoc) {
1782 // - its function-body shall be [...] a compound-statement that contains only
1783 switch (S->getStmtClass()) {
1784 case Stmt::NullStmtClass:
1785 // - null statements,
1786 return true;
1787
1788 case Stmt::DeclStmtClass:
1789 // - static_assert-declarations
1790 // - using-declarations,
1791 // - using-directives,
1792 // - typedef declarations and alias-declarations that do not define
1793 // classes or enumerations,
1794 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1795 return false;
1796 return true;
1797
1798 case Stmt::ReturnStmtClass:
1799 // - and exactly one return statement;
1800 if (isa<CXXConstructorDecl>(Dcl)) {
1801 // C++1y allows return statements in constexpr constructors.
1802 if (!Cxx1yLoc.isValid())
1803 Cxx1yLoc = S->getLocStart();
1804 return true;
1805 }
1806
1807 ReturnStmts.push_back(S->getLocStart());
1808 return true;
1809
1810 case Stmt::CompoundStmtClass: {
1811 // C++1y allows compound-statements.
1812 if (!Cxx1yLoc.isValid())
1813 Cxx1yLoc = S->getLocStart();
1814
1815 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001816 for (auto *BodyIt : CompStmt->body()) {
1817 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001818 Cxx1yLoc))
1819 return false;
1820 }
1821 return true;
1822 }
1823
1824 case Stmt::AttributedStmtClass:
1825 if (!Cxx1yLoc.isValid())
1826 Cxx1yLoc = S->getLocStart();
1827 return true;
1828
1829 case Stmt::IfStmtClass: {
1830 // C++1y allows if-statements.
1831 if (!Cxx1yLoc.isValid())
1832 Cxx1yLoc = S->getLocStart();
1833
1834 IfStmt *If = cast<IfStmt>(S);
1835 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1836 Cxx1yLoc))
1837 return false;
1838 if (If->getElse() &&
1839 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1840 Cxx1yLoc))
1841 return false;
1842 return true;
1843 }
1844
1845 case Stmt::WhileStmtClass:
1846 case Stmt::DoStmtClass:
1847 case Stmt::ForStmtClass:
1848 case Stmt::CXXForRangeStmtClass:
1849 case Stmt::ContinueStmtClass:
1850 // C++1y allows all of these. We don't allow them as extensions in C++11,
1851 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001852 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001853 break;
1854 if (!Cxx1yLoc.isValid())
1855 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001856 for (Stmt *SubStmt : S->children())
1857 if (SubStmt &&
1858 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001859 Cxx1yLoc))
1860 return false;
1861 return true;
1862
1863 case Stmt::SwitchStmtClass:
1864 case Stmt::CaseStmtClass:
1865 case Stmt::DefaultStmtClass:
1866 case Stmt::BreakStmtClass:
1867 // C++1y allows switch-statements, and since they don't need variable
1868 // mutation, we can reasonably allow them in C++11 as an extension.
1869 if (!Cxx1yLoc.isValid())
1870 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001871 for (Stmt *SubStmt : S->children())
1872 if (SubStmt &&
1873 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001874 Cxx1yLoc))
1875 return false;
1876 return true;
1877
1878 default:
1879 if (!isa<Expr>(S))
1880 break;
1881
1882 // C++1y allows expression-statements.
1883 if (!Cxx1yLoc.isValid())
1884 Cxx1yLoc = S->getLocStart();
1885 return true;
1886 }
1887
1888 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1889 << isa<CXXConstructorDecl>(Dcl);
1890 return false;
1891}
1892
Richard Smitheb3c10c2011-10-01 02:31:28 +00001893/// Check the body for the given constexpr function declaration only contains
1894/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1895///
1896/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001897bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001898 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001899 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001900 // The definition of a constexpr function shall satisfy the following
1901 // constraints: [...]
1902 // - its function-body shall be = delete, = default, or a
1903 // compound-statement
1904 //
Richard Smith74388b42012-02-04 00:33:54 +00001905 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001906 // In the definition of a constexpr constructor, [...]
1907 // - its function-body shall not be a function-try-block;
1908 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1909 << isa<CXXConstructorDecl>(Dcl);
1910 return false;
1911 }
1912
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001913 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001914
1915 // - its function-body shall be [...] a compound-statement that contains only
1916 // [... list of cases ...]
1917 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1918 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001919 for (auto *BodyIt : CompBody->body()) {
1920 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001921 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001922 }
1923
Richard Smithd9f663b2013-04-22 15:31:51 +00001924 if (Cxx1yLoc.isValid())
1925 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001926 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001927 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1928 : diag::ext_constexpr_body_invalid_stmt)
1929 << isa<CXXConstructorDecl>(Dcl);
1930
Richard Smitheb3c10c2011-10-01 02:31:28 +00001931 if (const CXXConstructorDecl *Constructor
1932 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1933 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001934 // DR1359:
1935 // - every non-variant non-static data member and base class sub-object
1936 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001937 // DR1460:
1938 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001939 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001940 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001941 if (Constructor->getNumCtorInitializers() == 0 &&
1942 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1944 return false;
1945 }
Richard Smithf368fb42011-10-10 16:38:04 +00001946 } else if (!Constructor->isDependentContext() &&
1947 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1949
1950 // Skip detailed checking if we have enough initializers, and we would
1951 // allow at most one initializer per member.
1952 bool AnyAnonStructUnionMembers = false;
1953 unsigned Fields = 0;
1954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1955 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001956 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001957 AnyAnonStructUnionMembers = true;
1958 break;
1959 }
1960 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001961 // DR1460:
1962 // - if the class is a union-like class, but is not a union, for each of
1963 // its anonymous union members having variant members, exactly one of
1964 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001965 if (AnyAnonStructUnionMembers ||
1966 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1967 // Check initialization of non-static data members. Base classes are
1968 // always initialized so do not need to be checked. Dependent bases
1969 // might not have initializers in the member initializer list.
1970 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001971 for (const auto *I: Constructor->inits()) {
1972 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001973 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001974 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001975 Inits.insert(ID->chain_begin(), ID->chain_end());
1976 }
1977
1978 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001979 for (auto *I : RD->fields())
1980 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001981 if (Diagnosed)
1982 return false;
1983 }
1984 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001985 } else {
1986 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001987 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001988 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001989 // otherwise if there's no return statement, the function cannot
1990 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001991 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001992 (Dcl->getReturnType()->isVoidType() ||
1993 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001994 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001995 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1996 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00001997 if (!OK)
1998 return false;
1999 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002000 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002001 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002002 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2003 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002004 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2005 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002006 }
2007 }
2008
Richard Smith74388b42012-02-04 00:33:54 +00002009 // C++11 [dcl.constexpr]p5:
2010 // if no function argument values exist such that the function invocation
2011 // substitution would produce a constant expression, the program is
2012 // ill-formed; no diagnostic required.
2013 // C++11 [dcl.constexpr]p3:
2014 // - every constructor call and implicit conversion used in initializing the
2015 // return value shall be one of those allowed in a constant expression.
2016 // C++11 [dcl.constexpr]p4:
2017 // - every constructor involved in initializing non-static data members and
2018 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002019 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002020 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002021 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002022 << isa<CXXConstructorDecl>(Dcl);
2023 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2024 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002025 // Don't return false here: we allow this for compatibility in
2026 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002027 }
2028
Richard Smitheb3c10c2011-10-01 02:31:28 +00002029 return true;
2030}
2031
Douglas Gregor61956c42008-10-31 09:07:45 +00002032/// isCurrentClassName - Determine whether the identifier II is the
2033/// name of the class type currently being defined. In the case of
2034/// nested classes, this will only return true if II is the name of
2035/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002036bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2037 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002038 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002039
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002040 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002041 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002042 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002043 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2044 } else
2045 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2046
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002047 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002048 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002049 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002050}
2051
Richard Smithfb8b7b92013-10-15 00:00:26 +00002052/// \brief Determine whether the identifier II is a typo for the name of
2053/// the class type currently being defined. If so, update it to the identifier
2054/// that should have been used.
2055bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2056 assert(getLangOpts().CPlusPlus && "No class names in C!");
2057
2058 if (!getLangOpts().SpellChecking)
2059 return false;
2060
2061 CXXRecordDecl *CurDecl;
2062 if (SS && SS->isSet() && !SS->isInvalid()) {
2063 DeclContext *DC = computeDeclContext(*SS, true);
2064 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2065 } else
2066 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2067
2068 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2069 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2070 < II->getLength()) {
2071 II = CurDecl->getIdentifier();
2072 return true;
2073 }
2074
2075 return false;
2076}
2077
Douglas Gregordc974572012-11-10 07:24:09 +00002078/// \brief Determine whether the given class is a base class of the given
2079/// class, including looking at dependent bases.
2080static bool findCircularInheritance(const CXXRecordDecl *Class,
2081 const CXXRecordDecl *Current) {
2082 SmallVector<const CXXRecordDecl*, 8> Queue;
2083
2084 Class = Class->getCanonicalDecl();
2085 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002086 for (const auto &I : Current->bases()) {
2087 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002088 if (!Base)
2089 continue;
2090
2091 Base = Base->getDefinition();
2092 if (!Base)
2093 continue;
2094
2095 if (Base->getCanonicalDecl() == Class)
2096 return true;
2097
2098 Queue.push_back(Base);
2099 }
2100
2101 if (Queue.empty())
2102 return false;
2103
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002104 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002105 }
2106
2107 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002108}
2109
Mike Stump11289f42009-09-09 15:08:12 +00002110/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002111///
2112/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2113/// and returns NULL otherwise.
2114CXXBaseSpecifier *
2115Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2116 SourceRange SpecifierRange,
2117 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002118 TypeSourceInfo *TInfo,
2119 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002120 QualType BaseType = TInfo->getType();
2121
Douglas Gregor463421d2009-03-03 04:44:36 +00002122 // C++ [class.union]p1:
2123 // A union shall not have base classes.
2124 if (Class->isUnion()) {
2125 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2126 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002127 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002128 }
2129
Douglas Gregor752a5952011-01-03 22:36:02 +00002130 if (EllipsisLoc.isValid() &&
2131 !TInfo->getType()->containsUnexpandedParameterPack()) {
2132 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2133 << TInfo->getTypeLoc().getSourceRange();
2134 EllipsisLoc = SourceLocation();
2135 }
Douglas Gregor62004702012-11-10 01:18:17 +00002136
2137 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2138
2139 if (BaseType->isDependentType()) {
2140 // Make sure that we don't have circular inheritance among our dependent
2141 // bases. For non-dependent bases, the check for completeness below handles
2142 // this.
2143 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2144 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2145 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002146 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002147 Diag(BaseLoc, diag::err_circular_inheritance)
2148 << BaseType << Context.getTypeDeclType(Class);
2149
2150 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2151 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2152 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002153
2154 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002155 }
2156 }
2157
Mike Stump11289f42009-09-09 15:08:12 +00002158 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002159 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002160 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002161 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002162
2163 // Base specifiers must be record types.
2164 if (!BaseType->isRecordType()) {
2165 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002166 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002167 }
2168
2169 // C++ [class.union]p1:
2170 // A union shall not be used as a base class.
2171 if (BaseType->isUnionType()) {
2172 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002173 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002174 }
2175
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002176 // For the MS ABI, propagate DLL attributes to base class templates.
2177 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2178 if (Attr *ClassAttr = getDLLAttr(Class)) {
2179 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2180 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002181 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2182 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002183 }
2184 }
2185 }
2186
Douglas Gregor463421d2009-03-03 04:44:36 +00002187 // C++ [class.derived]p2:
2188 // The class-name in a base-specifier shall not be an incompletely
2189 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002190 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002191 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002192 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002193 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002194 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002195
Eli Friedmanc96d4962009-08-15 21:55:26 +00002196 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002197 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002198 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002199 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002200 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002201 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002202 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002203
David Majnemer9b1754d2013-11-02 12:00:36 +00002204 // A class which contains a flexible array member is not suitable for use as a
2205 // base class:
2206 // - If the layout determines that a base comes before another base,
2207 // the flexible array member would index into the subsequent base.
2208 // - If the layout determines that base comes before the derived class,
2209 // the flexible array member would index into the derived class.
2210 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2211 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2212 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002214 }
2215
Anders Carlsson65c76d32011-03-25 14:55:14 +00002216 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002217 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002218 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002219 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002220 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002221 << CXXBaseDecl->getDeclName()
2222 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002223 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2224 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002225 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002226 }
2227
John McCall3696dcb2010-08-17 07:23:57 +00002228 if (BaseDecl->isInvalidDecl())
2229 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002230
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002231 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002232 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002233 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002234 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002235}
2236
Douglas Gregor556877c2008-04-13 21:30:24 +00002237/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2238/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002239/// example:
2240/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002241/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002242BaseResult
John McCall48871652010-08-21 09:40:31 +00002243Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002244 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002245 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002246 ParsedType basetype, SourceLocation BaseLoc,
2247 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002248 if (!classdecl)
2249 return true;
2250
Douglas Gregorc40290e2009-03-09 23:48:35 +00002251 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002252 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002253 if (!Class)
2254 return true;
2255
David Majnemer5ef4fe72014-06-13 06:43:46 +00002256 // We haven't yet attached the base specifiers.
2257 Class->setIsParsingBaseSpecifiers();
2258
Richard Smith4c96e992013-02-19 23:47:15 +00002259 // We do not support any C++11 attributes on base-specifiers yet.
2260 // Diagnose any attributes we see.
2261 if (!Attributes.empty()) {
2262 for (AttributeList *Attr = Attributes.getList(); Attr;
2263 Attr = Attr->getNext()) {
2264 if (Attr->isInvalid() ||
2265 Attr->getKind() == AttributeList::IgnoredAttribute)
2266 continue;
2267 Diag(Attr->getLoc(),
2268 Attr->getKind() == AttributeList::UnknownAttribute
2269 ? diag::warn_unknown_attribute_ignored
2270 : diag::err_base_specifier_attribute)
2271 << Attr->getName();
2272 }
2273 }
2274
Craig Topperc3ec1492014-05-26 06:22:03 +00002275 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002276 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002277
Douglas Gregor752a5952011-01-03 22:36:02 +00002278 if (EllipsisLoc.isInvalid() &&
2279 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002280 UPPC_BaseType))
2281 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002282
Douglas Gregor463421d2009-03-03 04:44:36 +00002283 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002284 Virtual, Access, TInfo,
2285 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002286 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002287 else
2288 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002289
Douglas Gregor463421d2009-03-03 04:44:36 +00002290 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002291}
Douglas Gregor556877c2008-04-13 21:30:24 +00002292
Nathan Sidwell44b21742015-01-19 01:44:02 +00002293/// Use small set to collect indirect bases. As this is only used
2294/// locally, there's no need to abstract the small size parameter.
2295typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2296
2297/// \brief Recursively add the bases of Type. Don't add Type itself.
2298static void
2299NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2300 const QualType &Type)
2301{
2302 // Even though the incoming type is a base, it might not be
2303 // a class -- it could be a template parm, for instance.
2304 if (auto Rec = Type->getAs<RecordType>()) {
2305 auto Decl = Rec->getAsCXXRecordDecl();
2306
2307 // Iterate over its bases.
2308 for (const auto &BaseSpec : Decl->bases()) {
2309 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2310 .getUnqualifiedType();
2311 if (Set.insert(Base).second)
2312 // If we've not already seen it, recurse.
2313 NoteIndirectBases(Context, Set, Base);
2314 }
2315 }
2316}
2317
Douglas Gregor463421d2009-03-03 04:44:36 +00002318/// \brief Performs the actual work of attaching the given base class
2319/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002320bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2321 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2322 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002323 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002324
2325 // Used to keep track of which base types we have already seen, so
2326 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002327 // that the key is always the unqualified canonical type of the base
2328 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002329 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2330
Nathan Sidwell44b21742015-01-19 01:44:02 +00002331 // Used to track indirect bases so we can see if a direct base is
2332 // ambiguous.
2333 IndirectBaseSet IndirectBaseTypes;
2334
Douglas Gregor29a92472008-10-22 17:49:05 +00002335 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002336 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002337 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002338 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002339 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002340 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002341 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002342
2343 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2344 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002345 // C++ [class.mi]p3:
2346 // A class shall not be specified as a direct base class of a
2347 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002348 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002349 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002350 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002351 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002352
2353 // Delete the duplicate base class specifier; we're going to
2354 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002355 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002356
2357 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002358 } else {
2359 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002360 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002361 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002362
2363 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002364 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002365 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2366
John McCalldb632ac2012-09-25 07:32:39 +00002367 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2368 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2369 if (Class->isInterface() &&
2370 (!RD->isInterface() ||
2371 KnownBase->getAccessSpecifier() != AS_public)) {
2372 // The Microsoft extension __interface does not permit bases that
2373 // are not themselves public interfaces.
2374 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2375 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2376 << RD->getSourceRange();
2377 Invalid = true;
2378 }
2379 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002380 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002381 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002382 }
2383 }
2384
2385 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002386 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002387
2388 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2389 // Check whether this direct base is inaccessible due to ambiguity.
2390 QualType BaseType = Bases[idx]->getType();
2391 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2392 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002393
Nathan Sidwell44b21742015-01-19 01:44:02 +00002394 if (IndirectBaseTypes.count(CanonicalBase)) {
2395 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2396 /*DetectVirtual=*/true);
2397 bool found
2398 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2399 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002400 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002401
2402 if (Paths.isAmbiguous(CanonicalBase))
2403 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2404 << BaseType << getAmbiguousPathsDisplayString(Paths)
2405 << Bases[idx]->getSourceRange();
2406 else
2407 assert(Bases[idx]->isVirtual());
2408 }
2409
2410 // Delete the base class specifier, since its data has been copied
2411 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002412 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002413 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002414
2415 return Invalid;
2416}
2417
2418/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2419/// class, after checking whether there are any duplicate base
2420/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002421void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2422 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2423 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002424 return;
2425
2426 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002427 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002428}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002429
Douglas Gregor36d1b142009-10-06 17:59:45 +00002430/// \brief Determine whether the type \p Derived is a C++ class that is
2431/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002432bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002433 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002434 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002435
Douglas Gregor45bb4832013-03-26 23:36:30 +00002436 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002437 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002438 return false;
2439
Douglas Gregor45bb4832013-03-26 23:36:30 +00002440 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002441 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002442 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002443
2444 // If either the base or the derived type is invalid, don't try to
2445 // check whether one is derived from the other.
2446 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2447 return false;
2448
Richard Smithdb0ac552015-12-18 22:40:25 +00002449 // FIXME: In a modules build, do we need the entire path to be visible for us
2450 // to be able to use the inheritance relationship?
2451 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2452 return false;
2453
Richard Smith0f59cb32015-12-18 21:45:41 +00002454 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002455}
2456
2457/// \brief Determine whether the type \p Derived is a C++ class that is
2458/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002459bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2460 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002462 return false;
2463
Douglas Gregor45bb4832013-03-26 23:36:30 +00002464 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002465 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002466 return false;
2467
Douglas Gregor45bb4832013-03-26 23:36:30 +00002468 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002469 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002470 return false;
2471
Richard Smithdb0ac552015-12-18 22:40:25 +00002472 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2473 return false;
2474
Douglas Gregor36d1b142009-10-06 17:59:45 +00002475 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2476}
2477
Anders Carlssona70cff62010-04-24 19:06:50 +00002478void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002479 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002480 assert(BasePathArray.empty() && "Base path array must be empty!");
2481 assert(Paths.isRecordingPaths() && "Must record paths!");
2482
2483 const CXXBasePath &Path = Paths.front();
2484
2485 // We first go backward and check if we have a virtual base.
2486 // FIXME: It would be better if CXXBasePath had the base specifier for
2487 // the nearest virtual base.
2488 unsigned Start = 0;
2489 for (unsigned I = Path.size(); I != 0; --I) {
2490 if (Path[I - 1].Base->isVirtual()) {
2491 Start = I - 1;
2492 break;
2493 }
2494 }
2495
2496 // Now add all bases.
2497 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002498 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002499}
2500
Douglas Gregor36d1b142009-10-06 17:59:45 +00002501/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2502/// conversion (where Derived and Base are class types) is
2503/// well-formed, meaning that the conversion is unambiguous (and
2504/// that all of the base classes are accessible). Returns true
2505/// and emits a diagnostic if the code is ill-formed, returns false
2506/// otherwise. Loc is the location where this routine should point to
2507/// if there is an error, and Range is the source range to highlight
2508/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002509///
2510/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2511/// diagnostic for the respective type of error will be suppressed, but the
2512/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002513bool
2514Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002515 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002516 unsigned AmbigiousBaseConvID,
2517 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002518 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002519 CXXCastPath *BasePath,
2520 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002521 // First, determine whether the path from Derived to Base is
2522 // ambiguous. This is slightly more expensive than checking whether
2523 // the Derived to Base conversion exists, because here we need to
2524 // explore multiple paths to determine if there is an ambiguity.
2525 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2526 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002527 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002528 assert(DerivationOkay &&
2529 "Can only be used with a derived-to-base conversion");
2530 (void)DerivationOkay;
2531
2532 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002533 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002534 // Check that the base class can be accessed.
2535 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2536 InaccessibleBaseID)) {
2537 case AR_inaccessible:
2538 return true;
2539 case AR_accessible:
2540 case AR_dependent:
2541 case AR_delayed:
2542 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002543 }
John McCall5b0829a2010-02-10 09:31:12 +00002544 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002545
2546 // Build a base path if necessary.
2547 if (BasePath)
2548 BuildBasePathArray(Paths, *BasePath);
2549 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002550 }
2551
David Majnemer626032f2013-06-22 06:43:58 +00002552 if (AmbigiousBaseConvID) {
2553 // We know that the derived-to-base conversion is ambiguous, and
2554 // we're going to produce a diagnostic. Perform the derived-to-base
2555 // search just one more time to compute all of the possible paths so
2556 // that we can print them out. This is more expensive than any of
2557 // the previous derived-to-base checks we've done, but at this point
2558 // performance isn't as much of an issue.
2559 Paths.clear();
2560 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002561 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002562 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2563 (void)StillOkay;
2564
2565 // Build up a textual representation of the ambiguous paths, e.g.,
2566 // D -> B -> A, that will be used to illustrate the ambiguous
2567 // conversions in the diagnostic. We only print one of the paths
2568 // to each base class subobject.
2569 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2570
2571 Diag(Loc, AmbigiousBaseConvID)
2572 << Derived << Base << PathDisplayStr << Range << Name;
2573 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002574 return true;
2575}
2576
2577bool
2578Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002579 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002580 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002581 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002582 return CheckDerivedToBaseConversion(
2583 Derived, Base, diag::err_upcast_to_inaccessible_base,
2584 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2585 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002586}
2587
2588
2589/// @brief Builds a string representing ambiguous paths from a
2590/// specific derived class to different subobjects of the same base
2591/// class.
2592///
2593/// This function builds a string that can be used in error messages
2594/// to show the different paths that one can take through the
2595/// inheritance hierarchy to go from the derived class to different
2596/// subobjects of a base class. The result looks something like this:
2597/// @code
2598/// struct D -> struct B -> struct A
2599/// struct D -> struct C -> struct A
2600/// @endcode
2601std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2602 std::string PathDisplayStr;
2603 std::set<unsigned> DisplayedPaths;
2604 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2605 Path != Paths.end(); ++Path) {
2606 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2607 // We haven't displayed a path to this particular base
2608 // class subobject yet.
2609 PathDisplayStr += "\n ";
2610 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2611 for (CXXBasePath::const_iterator Element = Path->begin();
2612 Element != Path->end(); ++Element)
2613 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2614 }
2615 }
2616
2617 return PathDisplayStr;
2618}
2619
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002620//===----------------------------------------------------------------------===//
2621// C++ class member Handling
2622//===----------------------------------------------------------------------===//
2623
Abramo Bagnarad7340582010-06-05 05:09:32 +00002624/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002625bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2626 SourceLocation ASLoc,
2627 SourceLocation ColonLoc,
2628 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002629 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002630 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002631 ASLoc, ColonLoc);
2632 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002633 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002634}
2635
Richard Smith18f07db2012-08-06 03:25:17 +00002636/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002637void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002638 if (D->isInvalidDecl())
2639 return;
2640
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002641 // We only care about "override" and "final" declarations.
2642 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2643 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002644
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002645 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002646
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002647 // We can't check dependent instance methods.
2648 if (MD && MD->isInstance() &&
2649 (MD->getParent()->hasAnyDependentBases() ||
2650 MD->getType()->isDependentType()))
2651 return;
2652
2653 if (MD && !MD->isVirtual()) {
2654 // If we have a non-virtual method, check if if hides a virtual method.
2655 // (In that case, it's most likely the method has the wrong type.)
2656 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2657 FindHiddenVirtualMethods(MD, OverloadedMethods);
2658
2659 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002660 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2661 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002662 diag::override_keyword_hides_virtual_member_function)
2663 << "override" << (OverloadedMethods.size() > 1);
2664 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002665 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002666 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002667 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2668 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002669 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002670 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2671 MD->setInvalidDecl();
2672 return;
2673 }
2674 // Fall through into the general case diagnostic.
2675 // FIXME: We might want to attempt typo correction here.
2676 }
2677
2678 if (!MD || !MD->isVirtual()) {
2679 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2680 Diag(OA->getLocation(),
2681 diag::override_keyword_only_allowed_on_virtual_member_functions)
2682 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2683 D->dropAttr<OverrideAttr>();
2684 }
2685 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2686 Diag(FA->getLocation(),
2687 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002688 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2689 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002690 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002691 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002692 return;
2693 }
Richard Smith18f07db2012-08-06 03:25:17 +00002694
Richard Smith18f07db2012-08-06 03:25:17 +00002695 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002696 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002697 // does not override a member function of a base class, the program is
2698 // ill-formed.
2699 bool HasOverriddenMethods =
2700 MD->begin_overridden_methods() != MD->end_overridden_methods();
2701 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2702 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2703 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002704}
2705
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002706void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2707 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2708 return;
2709 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2710 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2711 isa<CXXDestructorDecl>(MD))
2712 return;
2713
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002714 SourceLocation Loc = MD->getLocation();
2715 SourceLocation SpellingLoc = Loc;
2716 if (getSourceManager().isMacroArgExpansion(Loc))
2717 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2718 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2719 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002720 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002721
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002722 if (MD->size_overridden_methods() > 0) {
2723 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2724 << MD->getDeclName();
2725 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2726 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2727 }
2728}
2729
Richard Smith18f07db2012-08-06 03:25:17 +00002730/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002731/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002732/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002733bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2734 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002735 FinalAttr *FA = Old->getAttr<FinalAttr>();
2736 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002737 return false;
2738
2739 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002740 << New->getDeclName()
2741 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002742 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2743 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002744}
2745
Daniel Jasper0baec5492012-06-06 08:32:04 +00002746static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002747 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2748 // FIXME: Destruction of ObjC lifetime types has side-effects.
2749 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2750 return !RD->isCompleteDefinition() ||
2751 !RD->hasTrivialDefaultConstructor() ||
2752 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002753 return false;
2754}
2755
John McCall5e77d762013-04-16 07:28:30 +00002756static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002757 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002758 if (it->isDeclspecPropertyAttribute())
2759 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002760 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002761}
2762
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002763/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2764/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002765/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002766/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2767/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002768NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002769Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002770 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002771 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002772 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002773 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002774 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2775 DeclarationName Name = NameInfo.getName();
2776 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002777
2778 // For anonymous bitfields, the location should point to the type.
2779 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002780 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002781
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002782 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002783
John McCallb1cd7da2010-06-04 08:34:12 +00002784 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002785 assert(!DS.isFriendSpecified());
2786
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002787 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002788
John McCalldb632ac2012-09-25 07:32:39 +00002789 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2790 // The Microsoft extension __interface only permits public member functions
2791 // and prohibits constructors, destructors, operators, non-public member
2792 // functions, static methods and data members.
2793 unsigned InvalidDecl;
2794 bool ShowDeclName = true;
2795 if (!isFunc)
2796 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2797 else if (AS != AS_public)
2798 InvalidDecl = 2;
2799 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2800 InvalidDecl = 3;
2801 else switch (Name.getNameKind()) {
2802 case DeclarationName::CXXConstructorName:
2803 InvalidDecl = 4;
2804 ShowDeclName = false;
2805 break;
2806
2807 case DeclarationName::CXXDestructorName:
2808 InvalidDecl = 5;
2809 ShowDeclName = false;
2810 break;
2811
2812 case DeclarationName::CXXOperatorName:
2813 case DeclarationName::CXXConversionFunctionName:
2814 InvalidDecl = 6;
2815 break;
2816
2817 default:
2818 InvalidDecl = 0;
2819 break;
2820 }
2821
2822 if (InvalidDecl) {
2823 if (ShowDeclName)
2824 Diag(Loc, diag::err_invalid_member_in_interface)
2825 << (InvalidDecl-1) << Name;
2826 else
2827 Diag(Loc, diag::err_invalid_member_in_interface)
2828 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002829 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002830 }
2831 }
2832
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002833 // C++ 9.2p6: A member shall not be declared to have automatic storage
2834 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002835 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2836 // data members and cannot be applied to names declared const or static,
2837 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002838 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002839 case DeclSpec::SCS_unspecified:
2840 case DeclSpec::SCS_typedef:
2841 case DeclSpec::SCS_static:
2842 break;
2843 case DeclSpec::SCS_mutable:
2844 if (isFunc) {
2845 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Richard Smithb4a9e862013-04-12 22:46:28 +00002847 // FIXME: It would be nicer if the keyword was ignored only for this
2848 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002849 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002850 }
2851 break;
2852 default:
2853 Diag(DS.getStorageClassSpecLoc(),
2854 diag::err_storageclass_invalid_for_member);
2855 D.getMutableDeclSpec().ClearStorageClassSpecs();
2856 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002857 }
2858
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002859 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2860 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002861 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002862
David Blaikie35506f82013-01-30 01:22:18 +00002863 if (DS.isConstexprSpecified() && isInstField) {
2864 SemaDiagnosticBuilder B =
2865 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2866 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2867 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002868 B << 0 << 0;
2869 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2870 B << FixItHint::CreateRemoval(ConstexprLoc);
2871 else {
2872 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2873 D.getMutableDeclSpec().ClearConstexprSpec();
2874 const char *PrevSpec;
2875 unsigned DiagID;
2876 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2877 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2878 (void)Failed;
2879 assert(!Failed && "Making a constexpr member const shouldn't fail");
2880 }
David Blaikie35506f82013-01-30 01:22:18 +00002881 } else {
2882 B << 1;
2883 const char *PrevSpec;
2884 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002885 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002886 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2887 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002888 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002889 "This is the only DeclSpec that should fail to be applied");
2890 B << 1;
2891 } else {
2892 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2893 isInstField = false;
2894 }
2895 }
2896 }
2897
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002898 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002899 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002900 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002901
2902 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002903 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002904 Diag(Loc, diag::err_bad_variable_name)
2905 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002906 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002907 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002908
Benjamin Kramer365082d2012-05-19 16:34:46 +00002909 IdentifierInfo *II = Name.getAsIdentifierInfo();
2910
Douglas Gregor7c26c042011-09-21 14:40:46 +00002911 // Member field could not be with "template" keyword.
2912 // So TemplateParameterLists should be empty in this case.
2913 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002914 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002915 if (TemplateParams->size()) {
2916 // There is no such thing as a member field template.
2917 Diag(D.getIdentifierLoc(), diag::err_template_member)
2918 << II
2919 << SourceRange(TemplateParams->getTemplateLoc(),
2920 TemplateParams->getRAngleLoc());
2921 } else {
2922 // There is an extraneous 'template<>' for this member.
2923 Diag(TemplateParams->getTemplateLoc(),
2924 diag::err_template_member_noparams)
2925 << II
2926 << SourceRange(TemplateParams->getTemplateLoc(),
2927 TemplateParams->getRAngleLoc());
2928 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002929 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002930 }
2931
Douglas Gregora007d362010-10-13 22:19:53 +00002932 if (SS.isSet() && !SS.isInvalid()) {
2933 // The user provided a superfluous scope specifier inside a class
2934 // definition:
2935 //
2936 // class X {
2937 // int X::member;
2938 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002939 if (DeclContext *DC = computeDeclContext(SS, false))
2940 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002941 else
2942 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2943 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002944
Douglas Gregora007d362010-10-13 22:19:53 +00002945 SS.clear();
2946 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002947
John McCall5e77d762013-04-16 07:28:30 +00002948 AttributeList *MSPropertyAttr =
2949 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002950 if (MSPropertyAttr) {
2951 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2952 BitWidth, InitStyle, AS, MSPropertyAttr);
2953 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002955 isInstField = false;
2956 } else {
2957 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2958 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00002959 if (!Member)
2960 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002961 }
2962 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002963 Member = HandleDeclarator(S, D, TemplateParameterLists);
2964 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002965 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002966
2967 // Non-instance-fields can't have a bitfield.
2968 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002969 if (Member->isInvalidDecl()) {
2970 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002971 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002972 // C++ 9.6p3: A bit-field shall not be a static member.
2973 // "static member 'A' cannot be a bit-field"
2974 Diag(Loc, diag::err_static_not_bitfield)
2975 << Name << BitWidth->getSourceRange();
2976 } else if (isa<TypedefDecl>(Member)) {
2977 // "typedef member 'x' cannot be a bit-field"
2978 Diag(Loc, diag::err_typedef_not_bitfield)
2979 << Name << BitWidth->getSourceRange();
2980 } else {
2981 // A function typedef ("typedef int f(); f a;").
2982 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2983 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002984 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002985 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002986 }
Mike Stump11289f42009-09-09 15:08:12 +00002987
Craig Topperc3ec1492014-05-26 06:22:03 +00002988 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002989 Member->setInvalidDecl();
2990 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002991
2992 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Larisse Voufo39a1e502013-08-06 01:03:05 +00002994 // If we have declared a member function template or static data member
2995 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002996 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2997 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002998 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2999 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003000 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003001
Richard Smith18f07db2012-08-06 03:25:17 +00003002 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003003 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003004 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003005 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3006 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003007
Douglas Gregorf2f08062011-03-08 17:10:18 +00003008 if (VS.getLastLocation().isValid()) {
3009 // Update the end location of a method that has a virt-specifiers.
3010 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3011 MD->setRangeEnd(VS.getLastLocation());
3012 }
Richard Smith18f07db2012-08-06 03:25:17 +00003013
Anders Carlssonc87f8612011-01-20 06:29:02 +00003014 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003015
Douglas Gregor92751d42008-11-17 22:58:34 +00003016 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003017
Daniel Jasper0baec5492012-06-06 08:32:04 +00003018 if (isInstField) {
3019 FieldDecl *FD = cast<FieldDecl>(Member);
3020 FieldCollector->Add(FD);
3021
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003022 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003023 // Remember all explicit private FieldDecls that have a name, no side
3024 // effects and are not part of a dependent type declaration.
3025 if (!FD->isImplicit() && FD->getDeclName() &&
3026 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003027 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003028 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003029 !InitializationHasSideEffects(*FD))
3030 UnusedPrivateFields.insert(FD);
3031 }
3032 }
3033
John McCall48871652010-08-21 09:40:31 +00003034 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003035}
3036
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003037namespace {
3038 class UninitializedFieldVisitor
3039 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3040 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003041 // List of Decls to generate a warning on. Also remove Decls that become
3042 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003043 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003044 // List of base classes of the record. Classes are removed after their
3045 // initializers.
3046 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003047 // Vector of decls to be removed from the Decl set prior to visiting the
3048 // nodes. These Decls may have been initialized in the prior initializer.
3049 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003050 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003051 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003052 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003053 // InitList is true, special case initialization of FieldDecls matching
3054 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003055 bool InitList;
3056 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003057 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3058
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003059 public:
3060 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003061 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003062 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3063 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3064 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3065 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003066
Richard Trieufa1d0a72014-10-17 20:56:10 +00003067 // Returns true if the use of ME is not an uninitialized use.
3068 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3069 bool CheckReferenceOnly) {
3070 llvm::SmallVector<FieldDecl*, 4> Fields;
3071 bool ReferenceField = false;
3072 while (ME) {
3073 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3074 if (!FD)
3075 return false;
3076 Fields.push_back(FD);
3077 if (FD->getType()->isReferenceType())
3078 ReferenceField = true;
3079 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3080 }
3081
3082 // Binding a reference to an unintialized field is not an
3083 // uninitialized use.
3084 if (CheckReferenceOnly && !ReferenceField)
3085 return true;
3086
3087 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3088 // Discard the first field since it is the field decl that is being
3089 // initialized.
3090 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3091 UsedFieldIndex.push_back((*I)->getFieldIndex());
3092 }
3093
3094 for (auto UsedIter = UsedFieldIndex.begin(),
3095 UsedEnd = UsedFieldIndex.end(),
3096 OrigIter = InitFieldIndex.begin(),
3097 OrigEnd = InitFieldIndex.end();
3098 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3099 if (*UsedIter < *OrigIter)
3100 return true;
3101 if (*UsedIter > *OrigIter)
3102 break;
3103 }
3104
3105 return false;
3106 }
3107
Richard Trieu2d779b92014-10-01 03:44:58 +00003108 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3109 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003110 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3111 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003112
Richard Trieu1bc22c12013-09-13 03:20:53 +00003113 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3114 // or union.
3115 MemberExpr *FieldME = ME;
3116
Richard Trieu2d779b92014-10-01 03:44:58 +00003117 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3118
Richard Trieu1bc22c12013-09-13 03:20:53 +00003119 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003120 while (MemberExpr *SubME =
3121 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003122
Richard Trieufa1d0a72014-10-17 20:56:10 +00003123 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003124 return;
3125
Richard Trieufa1d0a72014-10-17 20:56:10 +00003126 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003127 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003128 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003129
Richard Trieu2d779b92014-10-01 03:44:58 +00003130 if (!FieldME->getType().isPODType(S.Context))
3131 AllPODFields = false;
3132
Richard Trieu3630c392014-11-21 03:10:30 +00003133 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003134 }
3135
Richard Trieu3630c392014-11-21 03:10:30 +00003136 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003137 return;
3138
Richard Trieu2d779b92014-10-01 03:44:58 +00003139 if (AddressOf && AllPODFields)
3140 return;
3141
Richard Trieu406e65c2013-09-20 03:03:06 +00003142 ValueDecl* FoundVD = FieldME->getMemberDecl();
3143
Richard Trieu3630c392014-11-21 03:10:30 +00003144 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3145 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3146 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3147 }
3148
3149 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3150 QualType T = BaseCast->getType();
3151 if (T->isPointerType() &&
3152 BaseClasses.count(T->getPointeeType())) {
3153 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3154 << T->getPointeeType() << FoundVD;
3155 }
3156 }
3157 }
3158
Richard Trieuef64e942013-10-25 00:56:00 +00003159 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003160 return;
3161
Richard Trieuef64e942013-10-25 00:56:00 +00003162 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003163
Richard Trieufa1d0a72014-10-17 20:56:10 +00003164 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3165 // Special checking for initializer lists.
3166 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3167 return;
3168 }
3169 } else {
3170 // Prevent double warnings on use of unbounded references.
3171 if (CheckReferenceOnly && !IsReference)
3172 return;
3173 }
Richard Trieuef64e942013-10-25 00:56:00 +00003174
3175 unsigned diag = IsReference
3176 ? diag::warn_reference_field_is_uninit
3177 : diag::warn_field_is_uninit;
3178 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3179 if (Constructor)
3180 S.Diag(Constructor->getLocation(),
3181 diag::note_uninit_in_this_constructor)
3182 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3183
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003184 }
3185
Richard Trieu2d779b92014-10-01 03:44:58 +00003186 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003187 E = E->IgnoreParens();
3188
3189 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003190 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3191 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003192 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003193 }
3194
3195 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003196 Visit(CO->getCond());
3197 HandleValue(CO->getTrueExpr(), AddressOf);
3198 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003199 return;
3200 }
3201
3202 if (BinaryConditionalOperator *BCO =
3203 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003204 Visit(BCO->getCond());
3205 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003206 return;
3207 }
3208
Richard Trieuabf6ec42014-08-27 22:15:10 +00003209 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003210 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003211 return;
3212 }
3213
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3215 switch (BO->getOpcode()) {
3216 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003217 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003218 case(BO_PtrMemD):
3219 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003220 HandleValue(BO->getLHS(), AddressOf);
3221 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003222 return;
3223 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003224 Visit(BO->getLHS());
3225 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003226 return;
3227 }
3228 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003229
3230 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003231 }
3232
Richard Trieufa1d0a72014-10-17 20:56:10 +00003233 void CheckInitListExpr(InitListExpr *ILE) {
3234 InitFieldIndex.push_back(0);
3235 for (auto Child : ILE->children()) {
3236 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3237 CheckInitListExpr(SubList);
3238 } else {
3239 Visit(Child);
3240 }
3241 ++InitFieldIndex.back();
3242 }
3243 InitFieldIndex.pop_back();
3244 }
3245
Richard Trieu8d08a272014-08-28 03:23:47 +00003246 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003247 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003248 // Remove Decls that may have been initialized in the previous
3249 // initializer.
3250 for (ValueDecl* VD : DeclsToRemove)
3251 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003252 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003253
Richard Trieu8d08a272014-08-28 03:23:47 +00003254 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003255 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3256
3257 if (ILE && Field) {
3258 InitList = true;
3259 InitListFieldDecl = Field;
3260 InitFieldIndex.clear();
3261 CheckInitListExpr(ILE);
3262 } else {
3263 InitList = false;
3264 Visit(E);
3265 }
3266
Richard Trieu8d08a272014-08-28 03:23:47 +00003267 if (Field)
3268 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003269 if (BaseClass)
3270 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003271 }
3272
Richard Trieu1bc22c12013-09-13 03:20:53 +00003273 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003274 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003275 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003276 }
3277
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003278 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003279 if (E->getCastKind() == CK_LValueToRValue) {
3280 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3281 return;
3282 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003283
3284 Inherited::VisitImplicitCastExpr(E);
3285 }
3286
Richard Trieu1bc22c12013-09-13 03:20:53 +00003287 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003288 if (E->getConstructor()->isCopyConstructor()) {
3289 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003290 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3291 if (ILE->getNumInits() == 1)
3292 ArgExpr = ILE->getInit(0);
3293 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3294 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003295 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003296 HandleValue(ArgExpr, false /*AddressOf*/);
3297 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003298 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003299 Inherited::VisitCXXConstructExpr(E);
3300 }
3301
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003302 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3303 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003304 if (isa<MemberExpr>(Callee)) {
3305 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003306 for (auto Arg : E->arguments())
3307 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003308 return;
3309 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003310
3311 Inherited::VisitCXXMemberCallExpr(E);
3312 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003313
Richard Trieu11fd0792014-08-26 04:30:55 +00003314 void VisitCallExpr(CallExpr *E) {
3315 // Treat std::move as a use.
3316 if (E->getNumArgs() == 1) {
3317 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003318 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3319 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003320 HandleValue(E->getArg(0), false /*AddressOf*/);
3321 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003322 }
3323 }
3324 }
3325
3326 Inherited::VisitCallExpr(E);
3327 }
3328
Richard Trieud4a01362014-10-31 21:10:22 +00003329 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3330 Expr *Callee = E->getCallee();
3331
3332 if (isa<UnresolvedLookupExpr>(Callee))
3333 return Inherited::VisitCXXOperatorCallExpr(E);
3334
3335 Visit(Callee);
3336 for (auto Arg : E->arguments())
3337 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3338 }
3339
Richard Trieu406e65c2013-09-20 03:03:06 +00003340 void VisitBinaryOperator(BinaryOperator *E) {
3341 // If a field assignment is detected, remove the field from the
3342 // uninitiailized field set.
3343 if (E->getOpcode() == BO_Assign)
3344 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003346 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003347 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003348
Richard Trieu52b8b602014-09-25 01:15:40 +00003349 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003350 HandleValue(E->getLHS(), false /*AddressOf*/);
3351 Visit(E->getRHS());
3352 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003353 }
3354
Richard Trieu406e65c2013-09-20 03:03:06 +00003355 Inherited::VisitBinaryOperator(E);
3356 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003357
3358 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003359 if (E->isIncrementDecrementOp()) {
3360 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3361 return;
3362 }
3363 if (E->getOpcode() == UO_AddrOf) {
3364 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3365 HandleValue(ME->getBase(), true /*AddressOf*/);
3366 return;
3367 }
3368 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003369
3370 Inherited::VisitUnaryOperator(E);
3371 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003372 };
Richard Trieuef64e942013-10-25 00:56:00 +00003373
3374 // Diagnose value-uses of fields to initialize themselves, e.g.
3375 // foo(foo)
3376 // where foo is not also a parameter to the constructor.
3377 // Also diagnose across field uninitialized use such as
3378 // x(y), y(x)
3379 // TODO: implement -Wuninitialized and fold this into that framework.
3380 static void DiagnoseUninitializedFields(
3381 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3382
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003383 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3384 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003385 return;
3386 }
3387
3388 if (Constructor->isInvalidDecl())
3389 return;
3390
3391 const CXXRecordDecl *RD = Constructor->getParent();
3392
Richard Trieu353a4b42014-10-22 05:21:59 +00003393 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003394 return;
3395
Richard Trieuef64e942013-10-25 00:56:00 +00003396 // Holds fields that are uninitialized.
3397 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3398
3399 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003400 for (auto *I : RD->decls()) {
3401 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003402 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003403 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003404 UninitializedFields.insert(IFD->getAnonField());
3405 }
3406 }
3407
Richard Trieu3630c392014-11-21 03:10:30 +00003408 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3409 for (auto I : RD->bases())
3410 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3411
3412 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003413 return;
3414
3415 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003416 UninitializedFields,
3417 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003418
Aaron Ballman0ad78302014-03-13 17:34:31 +00003419 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003420 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003421 break;
3422
Aaron Ballman0ad78302014-03-13 17:34:31 +00003423 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003424 if (!InitExpr)
3425 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003426
Richard Trieu8d08a272014-08-28 03:23:47 +00003427 if (CXXDefaultInitExpr *Default =
3428 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3429 InitExpr = Default->getExpr();
3430 if (!InitExpr)
3431 continue;
3432 // In class initializers will point to the constructor.
3433 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003434 FieldInit->getAnyMember(),
3435 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003436 } else {
3437 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003438 FieldInit->getAnyMember(),
3439 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003440 }
Richard Trieuef64e942013-10-25 00:56:00 +00003441 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003442 }
3443} // namespace
3444
Richard Smith74108172014-01-17 03:11:34 +00003445/// \brief Enter a new C++ default initializer scope. After calling this, the
3446/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3447/// parsing or instantiating the initializer failed.
3448void Sema::ActOnStartCXXInClassMemberInitializer() {
3449 // Create a synthetic function scope to represent the call to the constructor
3450 // that notionally surrounds a use of this initializer.
3451 PushFunctionScope();
3452}
3453
3454/// \brief This is invoked after parsing an in-class initializer for a
3455/// non-static C++ class member, and after instantiating an in-class initializer
3456/// in a class template. Such actions are deferred until the class is complete.
3457void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3458 SourceLocation InitLoc,
3459 Expr *InitExpr) {
3460 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003462
David Majnemer87ff66c2014-12-13 11:34:16 +00003463 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3464 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003465 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003466
3467 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003468 D->setInvalidDecl();
3469 if (FD)
3470 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003471 return;
3472 }
3473
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003474 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3475 FD->setInvalidDecl();
3476 FD->removeInClassInitializer();
3477 return;
3478 }
3479
Richard Smith938f40b2011-06-11 17:19:42 +00003480 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003481 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003482 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003483 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003484 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003485 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003486 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3487 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003488 if (Init.isInvalid()) {
3489 FD->setInvalidDecl();
3490 return;
3491 }
Richard Smith938f40b2011-06-11 17:19:42 +00003492 }
3493
Richard Smith945f8d32013-01-14 22:39:08 +00003494 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003495 // The initialization of each base and member constitutes a
3496 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003497 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003498 if (Init.isInvalid()) {
3499 FD->setInvalidDecl();
3500 return;
3501 }
3502
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003503 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003504
3505 FD->setInClassInitializer(InitExpr);
3506}
3507
Douglas Gregor15e77a22009-12-31 09:10:24 +00003508/// \brief Find the direct and/or virtual base specifiers that
3509/// correspond to the given base type, for use in base initialization
3510/// within a constructor.
3511static bool FindBaseInitializer(Sema &SemaRef,
3512 CXXRecordDecl *ClassDecl,
3513 QualType BaseType,
3514 const CXXBaseSpecifier *&DirectBaseSpec,
3515 const CXXBaseSpecifier *&VirtualBaseSpec) {
3516 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003517 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003518 for (const auto &Base : ClassDecl->bases()) {
3519 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003520 // We found a direct base of this type. That's what we're
3521 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003522 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003523 break;
3524 }
3525 }
3526
3527 // Check for a virtual base class.
3528 // FIXME: We might be able to short-circuit this if we know in advance that
3529 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003530 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003531 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3532 // We haven't found a base yet; search the class hierarchy for a
3533 // virtual base class.
3534 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3535 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003536 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3537 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003538 BaseType, Paths)) {
3539 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3540 Path != Paths.end(); ++Path) {
3541 if (Path->back().Base->isVirtual()) {
3542 VirtualBaseSpec = Path->back().Base;
3543 break;
3544 }
3545 }
3546 }
3547 }
3548
3549 return DirectBaseSpec || VirtualBaseSpec;
3550}
3551
Sebastian Redla74948d2011-09-24 17:48:25 +00003552/// \brief Handle a C++ member initializer using braced-init-list syntax.
3553MemInitResult
3554Sema::ActOnMemInitializer(Decl *ConstructorD,
3555 Scope *S,
3556 CXXScopeSpec &SS,
3557 IdentifierInfo *MemberOrBase,
3558 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003559 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003560 SourceLocation IdLoc,
3561 Expr *InitList,
3562 SourceLocation EllipsisLoc) {
3563 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003564 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003565 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003566}
3567
3568/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003569MemInitResult
John McCall48871652010-08-21 09:40:31 +00003570Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003571 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003572 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003573 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003574 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003575 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003576 SourceLocation IdLoc,
3577 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003578 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003579 SourceLocation RParenLoc,
3580 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003581 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003582 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003583 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003584 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003585}
3586
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003587namespace {
3588
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003589// Callback to only accept typo corrections that can be a valid C++ member
3590// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003591class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003592public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003593 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3594 : ClassDecl(ClassDecl) {}
3595
Craig Toppera798a9d2014-03-02 09:32:10 +00003596 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003597 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3598 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3599 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003600 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003601 }
3602 return false;
3603 }
3604
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003605private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003606 CXXRecordDecl *ClassDecl;
3607};
3608
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003609}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003610
Sebastian Redla74948d2011-09-24 17:48:25 +00003611/// \brief Handle a C++ member initializer.
3612MemInitResult
3613Sema::BuildMemInitializer(Decl *ConstructorD,
3614 Scope *S,
3615 CXXScopeSpec &SS,
3616 IdentifierInfo *MemberOrBase,
3617 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003618 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003619 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003620 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003621 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003622 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3623 if (!Res.isUsable())
3624 return true;
3625 Init = Res.get();
3626
Douglas Gregor71a57182009-06-22 23:20:33 +00003627 if (!ConstructorD)
3628 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003630 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003631
3632 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003633 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003634 if (!Constructor) {
3635 // The user wrote a constructor initializer on a function that is
3636 // not a C++ constructor. Ignore the error for now, because we may
3637 // have more member initializers coming; we'll diagnose it just
3638 // once in ActOnMemInitializers.
3639 return true;
3640 }
3641
3642 CXXRecordDecl *ClassDecl = Constructor->getParent();
3643
3644 // C++ [class.base.init]p2:
3645 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003646 // constructor's class and, if not found in that scope, are looked
3647 // up in the scope containing the constructor's definition.
3648 // [Note: if the constructor's class contains a member with the
3649 // same name as a direct or virtual base class of the class, a
3650 // mem-initializer-id naming the member or base class and composed
3651 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003652 // mem-initializer-id for the hidden base class may be specified
3653 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003654 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003655 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003656 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003657 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003658 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003659 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3660 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003661 if (EllipsisLoc.isValid())
3662 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003663 << MemberOrBase
3664 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003665
Sebastian Redla9351792012-02-11 23:51:47 +00003666 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003667 }
Francois Pichetd583da02010-12-04 09:14:42 +00003668 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003669 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003670 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003671 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003672 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003673
3674 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003675 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003676 } else if (DS.getTypeSpecType() == TST_decltype) {
3677 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00003678 } else {
3679 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3680 LookupParsedName(R, S, &SS);
3681
3682 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3683 if (!TyD) {
3684 if (R.isAmbiguous()) return true;
3685
John McCallda6841b2010-04-09 19:01:14 +00003686 // We don't want access-control diagnostics here.
3687 R.suppressDiagnostics();
3688
Douglas Gregora3b624a2010-01-19 06:46:48 +00003689 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3690 bool NotUnknownSpecialization = false;
3691 DeclContext *DC = computeDeclContext(SS, false);
3692 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3693 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3694
3695 if (!NotUnknownSpecialization) {
3696 // When the scope specifier can refer to a member of an unknown
3697 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003698 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3699 SS.getWithLocInContext(Context),
3700 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003701 if (BaseType.isNull())
3702 return true;
3703
Douglas Gregora3b624a2010-01-19 06:46:48 +00003704 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003705 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003706 }
3707 }
3708
Douglas Gregor15e77a22009-12-31 09:10:24 +00003709 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003710 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003711 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003712 (Corr = CorrectTypo(
3713 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3714 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3715 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003716 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003717 // We have found a non-static data member with a similar
3718 // name to what was typed; complain and initialize that
3719 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003720 diagnoseTypo(Corr,
3721 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3722 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003723 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003724 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003725 const CXXBaseSpecifier *DirectBaseSpec;
3726 const CXXBaseSpecifier *VirtualBaseSpec;
3727 if (FindBaseInitializer(*this, ClassDecl,
3728 Context.getTypeDeclType(Type),
3729 DirectBaseSpec, VirtualBaseSpec)) {
3730 // We have found a direct or virtual base class with a
3731 // similar name to what was typed; complain and initialize
3732 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003733 diagnoseTypo(Corr,
3734 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3735 << MemberOrBase << false,
3736 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003737
Richard Smithf9b15102013-08-17 00:46:16 +00003738 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3739 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003740 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003741 diag::note_base_class_specified_here)
3742 << BaseSpec->getType()
3743 << BaseSpec->getSourceRange();
3744
Douglas Gregor15e77a22009-12-31 09:10:24 +00003745 TyD = Type;
3746 }
3747 }
3748 }
3749
Douglas Gregora3b624a2010-01-19 06:46:48 +00003750 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003751 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003752 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003753 return true;
3754 }
John McCallb5a0d312009-12-21 10:41:20 +00003755 }
3756
Douglas Gregora3b624a2010-01-19 06:46:48 +00003757 if (BaseType.isNull()) {
3758 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003759 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003760 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003761 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3762 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003763 TInfo = Context.CreateTypeSourceInfo(BaseType);
3764 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3765 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3766 TL.setElaboratedKeywordLoc(SourceLocation());
3767 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3768 }
John McCallb5a0d312009-12-21 10:41:20 +00003769 }
3770 }
Mike Stump11289f42009-09-09 15:08:12 +00003771
John McCallbcd03502009-12-07 02:54:59 +00003772 if (!TInfo)
3773 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003774
Sebastian Redla9351792012-02-11 23:51:47 +00003775 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003776}
3777
Chandler Carruth599deef2011-09-03 01:14:15 +00003778/// Checks a member initializer expression for cases where reference (or
3779/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003780static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3781 Expr *Init,
3782 SourceLocation IdLoc) {
3783 QualType MemberTy = Member->getType();
3784
3785 // We only handle pointers and references currently.
3786 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3787 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3788 return;
3789
3790 const bool IsPointer = MemberTy->isPointerType();
3791 if (IsPointer) {
3792 if (const UnaryOperator *Op
3793 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3794 // The only case we're worried about with pointers requires taking the
3795 // address.
3796 if (Op->getOpcode() != UO_AddrOf)
3797 return;
3798
3799 Init = Op->getSubExpr();
3800 } else {
3801 // We only handle address-of expression initializers for pointers.
3802 return;
3803 }
3804 }
3805
Richard Smithe3b28bc2013-06-12 21:51:50 +00003806 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003807 // We only warn when referring to a non-reference parameter declaration.
3808 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3809 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003810 return;
3811
3812 S.Diag(Init->getExprLoc(),
3813 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3814 : diag::warn_bind_ref_member_to_parameter)
3815 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003816 } else {
3817 // Other initializers are fine.
3818 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003819 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003820
3821 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3822 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003823}
3824
John McCallfaf5fb42010-08-26 23:41:50 +00003825MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003826Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003827 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003828 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3829 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3830 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003831 "Member must be a FieldDecl or IndirectFieldDecl");
3832
Sebastian Redla9351792012-02-11 23:51:47 +00003833 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003834 return true;
3835
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003836 if (Member->isInvalidDecl())
3837 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003838
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003839 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003840 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003841 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003842 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003843 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003844 } else {
3845 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003846 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003847 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003848
Sebastian Redla9351792012-02-11 23:51:47 +00003849 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003850
Sebastian Redla9351792012-02-11 23:51:47 +00003851 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003852 // Can't check initialization for a member of dependent type or when
3853 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003854 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003855 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003856 bool InitList = false;
3857 if (isa<InitListExpr>(Init)) {
3858 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003859 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003860 }
3861
Chandler Carruthd44c3102010-12-06 09:23:57 +00003862 // Initialize the member.
3863 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003864 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3865 : InitializedEntity::InitializeMember(IndirectMember,
3866 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003867 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003868 InitList ? InitializationKind::CreateDirectList(IdLoc)
3869 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3870 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003871
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003872 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003873 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3874 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003875 if (MemberInit.isInvalid())
3876 return true;
3877
Richard Smith736a9472013-06-12 20:42:33 +00003878 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3879
Richard Smith945f8d32013-01-14 22:39:08 +00003880 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003881 // The initialization of each base and member constitutes a
3882 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003883 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003884 if (MemberInit.isInvalid())
3885 return true;
3886
Richard Smithd59b8322012-12-19 01:39:02 +00003887 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003888 }
3889
Chandler Carruthd44c3102010-12-06 09:23:57 +00003890 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003891 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3892 InitRange.getBegin(), Init,
3893 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003894 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003895 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3896 InitRange.getBegin(), Init,
3897 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003898 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003899}
3900
John McCallfaf5fb42010-08-26 23:41:50 +00003901MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003902Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003903 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003904 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003905 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003906 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003907 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003908 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003909
Sebastian Redl0501c632012-02-12 16:37:36 +00003910 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003911 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003912 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3913 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003914 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003915 }
3916
Sebastian Redla9351792012-02-11 23:51:47 +00003917 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003918 // Initialize the object.
3919 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3920 QualType(ClassDecl->getTypeForDecl(), 0));
3921 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003922 InitList ? InitializationKind::CreateDirectList(NameLoc)
3923 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3924 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003925 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003926 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003927 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003928 if (DelegationInit.isInvalid())
3929 return true;
3930
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003931 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3932 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003933
Richard Smith945f8d32013-01-14 22:39:08 +00003934 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003935 // The initialization of each base and member constitutes a
3936 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003937 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3938 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003939 if (DelegationInit.isInvalid())
3940 return true;
3941
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003942 // If we are in a dependent context, template instantiation will
3943 // perform this type-checking again. Just save the arguments that we
3944 // received in a ParenListExpr.
3945 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3946 // of the information that we have about the base
3947 // initializer. However, deconstructing the ASTs is a dicey process,
3948 // and this approach is far more likely to get the corner cases right.
3949 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003950 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003951
Sebastian Redla9351792012-02-11 23:51:47 +00003952 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003953 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003954 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003955}
3956
3957MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003958Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003959 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003960 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003961 SourceLocation BaseLoc
3962 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003963
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003964 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3965 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3966 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3967
3968 // C++ [class.base.init]p2:
3969 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003970 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003971 // of that class, the mem-initializer is ill-formed. A
3972 // mem-initializer-list can initialize a base class using any
3973 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003974 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003975
Sebastian Redla9351792012-02-11 23:51:47 +00003976 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003977 if (EllipsisLoc.isValid()) {
3978 // This is a pack expansion.
3979 if (!BaseType->containsUnexpandedParameterPack()) {
3980 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003981 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003982
Douglas Gregor44e7df62011-01-04 00:32:56 +00003983 EllipsisLoc = SourceLocation();
3984 }
3985 } else {
3986 // Check for any unexpanded parameter packs.
3987 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3988 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003989
Sebastian Redla9351792012-02-11 23:51:47 +00003990 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003991 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003992 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003993
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003994 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003995 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3996 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003997 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003998 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3999 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004000 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004001
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004002 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4003 VirtualBaseSpec);
4004
4005 // C++ [base.class.init]p2:
4006 // Unless the mem-initializer-id names a nonstatic data member of the
4007 // constructor's class or a direct or virtual base of that class, the
4008 // mem-initializer is ill-formed.
4009 if (!DirectBaseSpec && !VirtualBaseSpec) {
4010 // If the class has any dependent bases, then it's possible that
4011 // one of those types will resolve to the same type as
4012 // BaseType. Therefore, just treat this as a dependent base
4013 // class initialization. FIXME: Should we try to check the
4014 // initialization anyway? It seems odd.
4015 if (ClassDecl->hasAnyDependentBases())
4016 Dependent = true;
4017 else
4018 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4019 << BaseType << Context.getTypeDeclType(ClassDecl)
4020 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4021 }
4022 }
4023
4024 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004025 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004026
Sebastian Redla74948d2011-09-24 17:48:25 +00004027 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4028 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004029 InitRange.getBegin(), Init,
4030 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004031 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004032
4033 // C++ [base.class.init]p2:
4034 // If a mem-initializer-id is ambiguous because it designates both
4035 // a direct non-virtual base class and an inherited virtual base
4036 // class, the mem-initializer is ill-formed.
4037 if (DirectBaseSpec && VirtualBaseSpec)
4038 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004039 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004040
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004041 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004042 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004043 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004044
4045 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004046 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004047 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004048 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004049 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004050 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004051 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004052
4053 InitializedEntity BaseEntity =
4054 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4055 InitializationKind Kind =
4056 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4057 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4058 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004059 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004060 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004061 if (BaseInit.isInvalid())
4062 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004063
Richard Smith945f8d32013-01-14 22:39:08 +00004064 // C++11 [class.base.init]p7:
4065 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004066 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004067 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004068 if (BaseInit.isInvalid())
4069 return true;
4070
4071 // If we are in a dependent context, template instantiation will
4072 // perform this type-checking again. Just save the arguments that we
4073 // received in a ParenListExpr.
4074 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4075 // of the information that we have about the base
4076 // initializer. However, deconstructing the ASTs is a dicey process,
4077 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004078 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004079 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004080
Alexis Hunt1d792652011-01-08 20:30:50 +00004081 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004082 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004083 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004084 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004085 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004086}
4087
Sebastian Redl22653ba2011-08-30 19:58:05 +00004088// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004089static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4090 if (T.isNull()) T = E->getType();
4091 QualType TargetType = SemaRef.BuildReferenceType(
4092 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004093 SourceLocation ExprLoc = E->getLocStart();
4094 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4095 TargetType, ExprLoc);
4096
4097 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4098 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004099 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004100}
4101
Anders Carlsson1b00e242010-04-23 03:10:23 +00004102/// ImplicitInitializerKind - How an implicit base or member initializer should
4103/// initialize its base or member.
4104enum ImplicitInitializerKind {
4105 IIK_Default,
4106 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004107 IIK_Move,
4108 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004109};
4110
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004111static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004112BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004113 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004114 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004115 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004116 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004117 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004118 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4119 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004120
John McCalldadc5752010-08-24 06:29:42 +00004121 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004122
4123 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004124 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004125 case IIK_Default: {
4126 InitializationKind InitKind
4127 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004128 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4129 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004130 break;
4131 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004132
Sebastian Redl22653ba2011-08-30 19:58:05 +00004133 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004134 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004135 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004136 ParmVarDecl *Param = Constructor->getParamDecl(0);
4137 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004138
Anders Carlsson1b00e242010-04-23 03:10:23 +00004139 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004140 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004141 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004142 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004143 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004144
Eli Friedmanfa0df832012-02-02 03:46:19 +00004145 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4146
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004147 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004148 QualType ArgTy =
4149 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4150 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004151
Sebastian Redl22653ba2011-08-30 19:58:05 +00004152 if (Moving) {
4153 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4154 }
4155
John McCallcf142162010-08-07 06:22:56 +00004156 CXXCastPath BasePath;
4157 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004158 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4159 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004160 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004161 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004162
Anders Carlsson1b00e242010-04-23 03:10:23 +00004163 InitializationKind InitKind
4164 = InitializationKind::CreateDirect(Constructor->getLocation(),
4165 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004166 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4167 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004168 break;
4169 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004170 }
John McCallb268a282010-08-23 23:25:46 +00004171
Douglas Gregora40433a2010-12-07 00:41:46 +00004172 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004173 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004174 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004175
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004176 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004177 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004178 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4179 SourceLocation()),
4180 BaseSpec->isVirtual(),
4181 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004182 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004183 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004184 SourceLocation());
4185
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004186 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004187}
4188
Sebastian Redl22653ba2011-08-30 19:58:05 +00004189static bool RefersToRValueRef(Expr *MemRef) {
4190 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4191 return Referenced->getType()->isRValueReferenceType();
4192}
4193
Anders Carlsson3c1db572010-04-23 02:15:47 +00004194static bool
4195BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004196 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004197 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004198 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004199 if (Field->isInvalidDecl())
4200 return true;
4201
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004202 SourceLocation Loc = Constructor->getLocation();
4203
Sebastian Redl22653ba2011-08-30 19:58:05 +00004204 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4205 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004206 ParmVarDecl *Param = Constructor->getParamDecl(0);
4207 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004208
4209 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004210 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4211 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004212
Anders Carlsson423f5d82010-04-23 16:04:08 +00004213 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004214 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004215 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004216 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004217
Eli Friedmanfa0df832012-02-02 03:46:19 +00004218 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4219
Sebastian Redl22653ba2011-08-30 19:58:05 +00004220 if (Moving) {
4221 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4222 }
4223
Douglas Gregor94f9a482010-05-05 05:51:00 +00004224 // Build a reference to this field within the parameter.
4225 CXXScopeSpec SS;
4226 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4227 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004228 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4229 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004230 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004231 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004232 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004233 ParamType, Loc,
4234 /*IsArrow=*/false,
4235 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004236 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004237 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004238 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004239 /*TemplateArgs=*/nullptr,
4240 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004241 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004242 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004243
4244 // C++11 [class.copy]p15:
4245 // - if a member m has rvalue reference type T&&, it is direct-initialized
4246 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004247 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004248 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004249 }
4250
Douglas Gregor94f9a482010-05-05 05:51:00 +00004251 // When the field we are copying is an array, create index variables for
4252 // each dimension of the array. We use these index variables to subscript
4253 // the source array, and other clients (e.g., CodeGen) will perform the
4254 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004255 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004256 QualType BaseType = Field->getType();
4257 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004258 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004259 while (const ConstantArrayType *Array
4260 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004261 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004262 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00004263 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004264 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004265 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004266 llvm::raw_svector_ostream OS(Str);
4267 OS << "__i" << IndexVariables.size();
4268 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4269 }
4270 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00004271 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004272 IterationVarName, SizeType,
4273 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004274 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004275 IndexVariables.push_back(IterationVar);
4276
4277 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00004278 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00004279 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004280 assert(!IterationVarRef.isInvalid() &&
4281 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004282 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00004283 assert(!IterationVarRef.isInvalid() &&
4284 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00004285
Douglas Gregor94f9a482010-05-05 05:51:00 +00004286 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004287 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4288 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00004289 Loc);
4290 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00004291 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004292
Douglas Gregor94f9a482010-05-05 05:51:00 +00004293 BaseType = Array->getElementType();
4294 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004295
4296 // The array subscript expression is an lvalue, which is wrong for moving.
4297 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004298 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004299
Douglas Gregor94f9a482010-05-05 05:51:00 +00004300 // Construct the entity that we will be initializing. For an array, this
4301 // will be first element in the array, which may require several levels
4302 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004303 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004304 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00004305 if (Indirect)
4306 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4307 else
4308 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00004309 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4310 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4311 0,
4312 Entities.back()));
4313
4314 // Direct-initialize to use the copy constructor.
4315 InitializationKind InitKind =
4316 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4317
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004318 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00004319 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4320 CtorArgE);
4321
John McCalldadc5752010-08-24 06:29:42 +00004322 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00004323 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004324 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004325 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004326 if (MemberInit.isInvalid())
4327 return true;
4328
Douglas Gregor493627b2011-08-10 15:22:55 +00004329 if (Indirect) {
4330 assert(IndexVariables.size() == 0 &&
4331 "Indirect field improperly initialized");
4332 CXXMemberInit
4333 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4334 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004335 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004336 Loc);
4337 } else
4338 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004339 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004340 Loc,
4341 IndexVariables.data(),
4342 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00004343 return false;
4344 }
4345
Richard Smithc2bc61b2013-03-18 21:12:30 +00004346 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4347 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004348
Anders Carlsson3c1db572010-04-23 02:15:47 +00004349 QualType FieldBaseElementType =
4350 SemaRef.Context.getBaseElementType(Field->getType());
4351
Anders Carlsson3c1db572010-04-23 02:15:47 +00004352 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004353 InitializedEntity InitEntity
4354 = Indirect? InitializedEntity::InitializeMember(Indirect)
4355 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004356 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004357 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004358
4359 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4360 ExprResult MemberInit =
4361 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004362
Douglas Gregora40433a2010-12-07 00:41:46 +00004363 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004364 if (MemberInit.isInvalid())
4365 return true;
4366
Douglas Gregor493627b2011-08-10 15:22:55 +00004367 if (Indirect)
4368 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4369 Indirect, Loc,
4370 Loc,
4371 MemberInit.get(),
4372 Loc);
4373 else
4374 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4375 Field, Loc, Loc,
4376 MemberInit.get(),
4377 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004378 return false;
4379 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004380
Alexis Hunt8b455182011-05-17 00:19:05 +00004381 if (!Field->getParent()->isUnion()) {
4382 if (FieldBaseElementType->isReferenceType()) {
4383 SemaRef.Diag(Constructor->getLocation(),
4384 diag::err_uninitialized_member_in_ctor)
4385 << (int)Constructor->isImplicit()
4386 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4387 << 0 << Field->getDeclName();
4388 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4389 return true;
4390 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004391
Alexis Hunt8b455182011-05-17 00:19:05 +00004392 if (FieldBaseElementType.isConstQualified()) {
4393 SemaRef.Diag(Constructor->getLocation(),
4394 diag::err_uninitialized_member_in_ctor)
4395 << (int)Constructor->isImplicit()
4396 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4397 << 1 << Field->getDeclName();
4398 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4399 return true;
4400 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004401 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004402
David Blaikiebbafb8a2012-03-11 07:00:24 +00004403 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004404 FieldBaseElementType->isObjCRetainableType() &&
4405 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4406 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004407 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004408 // Default-initialize Objective-C pointers to NULL.
4409 CXXMemberInit
4410 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4411 Loc, Loc,
4412 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4413 Loc);
4414 return false;
4415 }
4416
Anders Carlsson3c1db572010-04-23 02:15:47 +00004417 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004418 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004419 return false;
4420}
John McCallbc83b3f2010-05-20 23:23:51 +00004421
4422namespace {
4423struct BaseAndFieldInfo {
4424 Sema &S;
4425 CXXConstructorDecl *Ctor;
4426 bool AnyErrorsInInits;
4427 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004428 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004429 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004430 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004431
4432 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4433 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004434 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004435 if (Ctor->getInheritedConstructor())
4436 IIK = IIK_Inherit;
4437 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004438 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004439 else if (Generated && Ctor->isMoveConstructor())
4440 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004441 else
4442 IIK = IIK_Default;
4443 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004444
4445 bool isImplicitCopyOrMove() const {
4446 switch (IIK) {
4447 case IIK_Copy:
4448 case IIK_Move:
4449 return true;
4450
4451 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004452 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004453 return false;
4454 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004455
4456 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004457 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004458
4459 bool addFieldInitializer(CXXCtorInitializer *Init) {
4460 AllToInit.push_back(Init);
4461
4462 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004463 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004464 S.UnusedPrivateFields.remove(Init->getAnyMember());
4465
4466 return false;
4467 }
John McCallbc83b3f2010-05-20 23:23:51 +00004468
Richard Smithab44d5b2013-12-10 08:25:00 +00004469 bool isInactiveUnionMember(FieldDecl *Field) {
4470 RecordDecl *Record = Field->getParent();
4471 if (!Record->isUnion())
4472 return false;
4473
Richard Smith8d183852013-12-10 20:56:03 +00004474 if (FieldDecl *Active =
4475 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004476 return Active != Field->getCanonicalDecl();
4477
4478 // In an implicit copy or move constructor, ignore any in-class initializer.
4479 if (isImplicitCopyOrMove())
4480 return true;
4481
4482 // If there's no explicit initialization, the field is active only if it
4483 // has an in-class initializer...
4484 if (Field->hasInClassInitializer())
4485 return false;
4486 // ... or it's an anonymous struct or union whose class has an in-class
4487 // initializer.
4488 if (!Field->isAnonymousStructOrUnion())
4489 return true;
4490 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4491 return !FieldRD->hasInClassInitializer();
4492 }
4493
4494 /// \brief Determine whether the given field is, or is within, a union member
4495 /// that is inactive (because there was an initializer given for a different
4496 /// member of the union, or because the union was not initialized at all).
4497 bool isWithinInactiveUnionMember(FieldDecl *Field,
4498 IndirectFieldDecl *Indirect) {
4499 if (!Indirect)
4500 return isInactiveUnionMember(Field);
4501
Aaron Ballman29c94602014-03-07 18:36:15 +00004502 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004503 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004504 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004505 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004506 }
4507 return false;
4508 }
4509};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004510}
Richard Smithc94ec842011-09-19 13:34:43 +00004511
Douglas Gregor10f939c2011-11-02 23:04:16 +00004512/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4513/// array type.
4514static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4515 if (T->isIncompleteArrayType())
4516 return true;
4517
4518 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4519 if (!ArrayT->getSize())
4520 return true;
4521
4522 T = ArrayT->getElementType();
4523 }
4524
4525 return false;
4526}
4527
Richard Smith938f40b2011-06-11 17:19:42 +00004528static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004529 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004530 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004531 if (Field->isInvalidDecl())
4532 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004533
Chandler Carruth139e9622010-06-30 02:59:29 +00004534 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004535 if (CXXCtorInitializer *Init =
4536 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004537 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004538
Richard Smithab44d5b2013-12-10 08:25:00 +00004539 // C++11 [class.base.init]p8:
4540 // if the entity is a non-static data member that has a
4541 // brace-or-equal-initializer and either
4542 // -- the constructor's class is a union and no other variant member of that
4543 // union is designated by a mem-initializer-id or
4544 // -- the constructor's class is not a union, and, if the entity is a member
4545 // of an anonymous union, no other member of that union is designated by
4546 // a mem-initializer-id,
4547 // the entity is initialized as specified in [dcl.init].
4548 //
4549 // We also apply the same rules to handle anonymous structs within anonymous
4550 // unions.
4551 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4552 return false;
4553
Douglas Gregor7db3e952011-11-28 20:03:15 +00004554 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004555 ExprResult DIE =
4556 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4557 if (DIE.isInvalid())
4558 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004559 CXXCtorInitializer *Init;
4560 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004561 Init = new (SemaRef.Context)
4562 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4563 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004564 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004565 Init = new (SemaRef.Context)
4566 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4567 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004568 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004569 }
4570
Douglas Gregor10f939c2011-11-02 23:04:16 +00004571 // Don't initialize incomplete or zero-length arrays.
4572 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4573 return false;
4574
John McCallbc83b3f2010-05-20 23:23:51 +00004575 // Don't try to build an implicit initializer if there were semantic
4576 // errors in any of the initializers (and therefore we might be
4577 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004578 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004579 return false;
4580
Craig Topperc3ec1492014-05-26 06:22:03 +00004581 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004582 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4583 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004584 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004585
Richard Smith0a8cfc72012-08-07 21:30:42 +00004586 if (!Init)
4587 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004588
Richard Smith0a8cfc72012-08-07 21:30:42 +00004589 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004590}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004591
4592bool
4593Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4594 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004595 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004596 Constructor->setNumCtorInitializers(1);
4597 CXXCtorInitializer **initializer =
4598 new (Context) CXXCtorInitializer*[1];
4599 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4600 Constructor->setCtorInitializers(initializer);
4601
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004602 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004603 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004604 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4605 }
4606
Alexis Hunte2622992011-05-05 00:05:47 +00004607 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004608
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004609 DiagnoseUninitializedFields(*this, Constructor);
4610
Alexis Hunt61bc1732011-05-01 07:04:31 +00004611 return false;
4612}
Douglas Gregor493627b2011-08-10 15:22:55 +00004613
David Blaikie3fc2f912013-01-17 05:26:25 +00004614bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4615 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004616 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004617 // Just store the initializers as written, they will be checked during
4618 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004619 if (!Initializers.empty()) {
4620 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004621 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004622 new (Context) CXXCtorInitializer*[Initializers.size()];
4623 memcpy(baseOrMemberInitializers, Initializers.data(),
4624 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004625 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004626 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004627
4628 // Let template instantiation know whether we had errors.
4629 if (AnyErrors)
4630 Constructor->setInvalidDecl();
4631
Anders Carlssondb0a9652010-04-02 06:26:44 +00004632 return false;
4633 }
4634
John McCallbc83b3f2010-05-20 23:23:51 +00004635 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004636
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004637 // We need to build the initializer AST according to order of construction
4638 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004639 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004640 if (!ClassDecl)
4641 return true;
4642
Eli Friedman9cf6b592009-11-09 19:20:36 +00004643 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004644
David Blaikie3fc2f912013-01-17 05:26:25 +00004645 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004646 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004647
Anders Carlssondb0a9652010-04-02 06:26:44 +00004648 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004649 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004650 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004651 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004652
4653 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004654 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004655 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004656 if (FD && FD->getParent()->isUnion())
4657 Info.ActiveUnionMember.insert(std::make_pair(
4658 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4659 }
4660 } else if (FieldDecl *FD = Member->getMember()) {
4661 if (FD->getParent()->isUnion())
4662 Info.ActiveUnionMember.insert(std::make_pair(
4663 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4664 }
4665 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004666 }
4667
Anders Carlsson43c64af2010-04-21 19:52:01 +00004668 // Keep track of the direct virtual bases.
4669 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004670 for (auto &I : ClassDecl->bases()) {
4671 if (I.isVirtual())
4672 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004673 }
4674
Anders Carlssondb0a9652010-04-02 06:26:44 +00004675 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004676 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004677 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004678 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004679 // [class.base.init]p7, per DR257:
4680 // A mem-initializer where the mem-initializer-id names a virtual base
4681 // class is ignored during execution of a constructor of any class that
4682 // is not the most derived class.
4683 if (ClassDecl->isAbstract()) {
4684 // FIXME: Provide a fixit to remove the base specifier. This requires
4685 // tracking the location of the associated comma for a base specifier.
4686 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004687 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004688 DiagnoseAbstractType(ClassDecl);
4689 }
4690
John McCallbc83b3f2010-05-20 23:23:51 +00004691 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004692 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4693 // [class.base.init]p8, per DR257:
4694 // If a given [...] base class is not named by a mem-initializer-id
4695 // [...] and the entity is not a virtual base class of an abstract
4696 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004697 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004698 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004699 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004700 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004701 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004702 HadError = true;
4703 continue;
4704 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004705
John McCallbc83b3f2010-05-20 23:23:51 +00004706 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004707 }
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
John McCallbc83b3f2010-05-20 23:23:51 +00004710 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004711 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004712 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004713 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004714 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004715
Alexis Hunt1d792652011-01-08 20:30:50 +00004716 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004717 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004718 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004719 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004720 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004721 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004722 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004723 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004724 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004725 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004726 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004727
John McCallbc83b3f2010-05-20 23:23:51 +00004728 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004729 }
4730 }
Mike Stump11289f42009-09-09 15:08:12 +00004731
John McCallbc83b3f2010-05-20 23:23:51 +00004732 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004733 for (auto *Mem : ClassDecl->decls()) {
4734 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004735 // C++ [class.bit]p2:
4736 // A declaration for a bit-field that omits the identifier declares an
4737 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4738 // initialized.
4739 if (F->isUnnamedBitfield())
4740 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004741
Sebastian Redl22653ba2011-08-30 19:58:05 +00004742 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004743 // handle anonymous struct/union fields based on their individual
4744 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004745 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004746 continue;
4747
4748 if (CollectFieldInitializer(*this, Info, F))
4749 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004750 continue;
4751 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004752
4753 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004754 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004755 continue;
4756
Aaron Ballman629afae2014-03-07 19:56:05 +00004757 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004758 if (F->getType()->isIncompleteArrayType()) {
4759 assert(ClassDecl->hasFlexibleArrayMember() &&
4760 "Incomplete array type is not valid");
4761 continue;
4762 }
4763
Douglas Gregor493627b2011-08-10 15:22:55 +00004764 // Initialize each field of an anonymous struct individually.
4765 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4766 HadError = true;
4767
4768 continue;
4769 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004770 }
Mike Stump11289f42009-09-09 15:08:12 +00004771
David Blaikie3fc2f912013-01-17 05:26:25 +00004772 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004773 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004774 Constructor->setNumCtorInitializers(NumInitializers);
4775 CXXCtorInitializer **baseOrMemberInitializers =
4776 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004777 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004778 NumInitializers * sizeof(CXXCtorInitializer*));
4779 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004780
John McCalla6309952010-03-16 21:39:52 +00004781 // Constructors implicitly reference the base and member
4782 // destructors.
4783 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4784 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004785 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004786
4787 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004788}
4789
David Blaikieb61b8152013-01-17 08:49:22 +00004790static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004791 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004792 const RecordDecl *RD = RT->getDecl();
4793 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004794 for (auto *Field : RD->fields())
4795 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004796 return;
4797 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004798 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004799 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004800}
4801
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004802static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4803 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004804}
4805
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004806static const void *GetKeyForMember(ASTContext &Context,
4807 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004808 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004809 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004810
Richard Smithcd45dbc2014-04-19 03:48:30 +00004811 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004812}
4813
David Blaikie3fc2f912013-01-17 05:26:25 +00004814static void DiagnoseBaseOrMemInitializerOrder(
4815 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4816 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004817 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004818 return;
Mike Stump11289f42009-09-09 15:08:12 +00004819
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004820 // Don't check initializers order unless the warning is enabled at the
4821 // location of at least one initializer.
4822 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004823 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004824 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004825 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4826 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004827 ShouldCheckOrder = true;
4828 break;
4829 }
4830 }
4831 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004832 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004833
John McCallbb7b6582010-04-10 07:37:23 +00004834 // Build the list of bases and members in the order that they'll
4835 // actually be initialized. The explicit initializers should be in
4836 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004837 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004839 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4840
John McCallbb7b6582010-04-10 07:37:23 +00004841 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004842 for (const auto &VBase : ClassDecl->vbases())
4843 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004844
John McCallbb7b6582010-04-10 07:37:23 +00004845 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004846 for (const auto &Base : ClassDecl->bases()) {
4847 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004848 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004849 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
John McCallbb7b6582010-04-10 07:37:23 +00004852 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004853 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004854 if (Field->isUnnamedBitfield())
4855 continue;
4856
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004857 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004858 }
4859
John McCallbb7b6582010-04-10 07:37:23 +00004860 unsigned NumIdealInits = IdealInitKeys.size();
4861 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004862
Craig Topperc3ec1492014-05-26 06:22:03 +00004863 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004864 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004865 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004866 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004867
4868 // Scan forward to try to find this initializer in the idealized
4869 // initializers list.
4870 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4871 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004872 break;
John McCallbb7b6582010-04-10 07:37:23 +00004873
4874 // If we didn't find this initializer, it must be because we
4875 // scanned past it on a previous iteration. That can only
4876 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004877 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004878 Sema::SemaDiagnosticBuilder D =
4879 SemaRef.Diag(PrevInit->getSourceLocation(),
4880 diag::warn_initializer_out_of_order);
4881
Francois Pichetd583da02010-12-04 09:14:42 +00004882 if (PrevInit->isAnyMemberInitializer())
4883 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004884 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004885 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004886
Francois Pichetd583da02010-12-04 09:14:42 +00004887 if (Init->isAnyMemberInitializer())
4888 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004889 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004890 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004891
4892 // Move back to the initializer's location in the ideal list.
4893 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4894 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004895 break;
John McCallbb7b6582010-04-10 07:37:23 +00004896
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004897 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004898 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004899 }
John McCallbb7b6582010-04-10 07:37:23 +00004900
4901 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004902 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004903}
4904
John McCall23eebd92010-04-10 09:28:51 +00004905namespace {
4906bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004907 CXXCtorInitializer *Init,
4908 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004909 if (!PrevInit) {
4910 PrevInit = Init;
4911 return false;
4912 }
4913
Douglas Gregorea306a12013-03-25 23:28:23 +00004914 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004915 S.Diag(Init->getSourceLocation(),
4916 diag::err_multiple_mem_initialization)
4917 << Field->getDeclName()
4918 << Init->getSourceRange();
4919 else {
John McCall424cec92011-01-19 06:33:43 +00004920 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004921 assert(BaseClass && "neither field nor base");
4922 S.Diag(Init->getSourceLocation(),
4923 diag::err_multiple_base_initialization)
4924 << QualType(BaseClass, 0)
4925 << Init->getSourceRange();
4926 }
4927 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4928 << 0 << PrevInit->getSourceRange();
4929
4930 return true;
4931}
4932
Alexis Hunt1d792652011-01-08 20:30:50 +00004933typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004934typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4935
4936bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004937 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004938 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004939 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004940 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004941 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004942
4943 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004944 if (Parent->isUnion()) {
4945 UnionEntry &En = Unions[Parent];
4946 if (En.first && En.first != Child) {
4947 S.Diag(Init->getSourceLocation(),
4948 diag::err_multiple_mem_union_initialization)
4949 << Field->getDeclName()
4950 << Init->getSourceRange();
4951 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4952 << 0 << En.second->getSourceRange();
4953 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004954 }
4955 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004956 En.first = Child;
4957 En.second = Init;
4958 }
David Blaikie0f65d592011-11-17 06:01:57 +00004959 if (!Parent->isAnonymousStructOrUnion())
4960 return false;
John McCall23eebd92010-04-10 09:28:51 +00004961 }
4962
4963 Child = Parent;
4964 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004965 }
John McCall23eebd92010-04-10 09:28:51 +00004966
4967 return false;
4968}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004969}
John McCall23eebd92010-04-10 09:28:51 +00004970
Anders Carlssone857b292010-04-02 03:37:03 +00004971/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004972void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004973 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004974 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004975 bool AnyErrors) {
4976 if (!ConstructorDecl)
4977 return;
4978
4979 AdjustDeclIfTemplate(ConstructorDecl);
4980
4981 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004982 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004983
4984 if (!Constructor) {
4985 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4986 return;
4987 }
4988
John McCall23eebd92010-04-10 09:28:51 +00004989 // Mapping for the duplicate initializers check.
4990 // For member initializers, this is keyed with a FieldDecl*.
4991 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004992 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004993
4994 // Mapping for the inconsistent anonymous-union initializers check.
4995 RedundantUnionMap MemberUnions;
4996
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004997 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004998 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004999 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00005000
Abramo Bagnara341d7832010-05-26 18:09:23 +00005001 // Set the source order index.
5002 Init->setSourceOrder(i);
5003
Francois Pichetd583da02010-12-04 09:14:42 +00005004 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005005 const void *Key = GetKeyForMember(Context, Init);
5006 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005007 CheckRedundantUnionInit(*this, Init, MemberUnions))
5008 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005009 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005010 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005011 if (CheckRedundantInit(*this, Init, Members[Key]))
5012 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005013 } else {
5014 assert(Init->isDelegatingInitializer());
5015 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005016 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005017 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005018 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005019 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005020 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005021 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005022 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005023 // Return immediately as the initializer is set.
5024 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005025 }
Anders Carlssone857b292010-04-02 03:37:03 +00005026 }
5027
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005028 if (HadError)
5029 return;
5030
David Blaikie3fc2f912013-01-17 05:26:25 +00005031 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005032
David Blaikie3fc2f912013-01-17 05:26:25 +00005033 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005034
Richard Trieuef64e942013-10-25 00:56:00 +00005035 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005036}
5037
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005038void
John McCalla6309952010-03-16 21:39:52 +00005039Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5040 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005041 // Ignore dependent contexts. Also ignore unions, since their members never
5042 // have destructors implicitly called.
5043 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005044 return;
John McCall1064d7e2010-03-16 05:22:47 +00005045
5046 // FIXME: all the access-control diagnostics are positioned on the
5047 // field/base declaration. That's probably good; that said, the
5048 // user might reasonably want to know why the destructor is being
5049 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005050
Anders Carlssondee9a302009-11-17 04:44:12 +00005051 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005052 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005053 if (Field->isInvalidDecl())
5054 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005055
5056 // Don't destroy incomplete or zero-length arrays.
5057 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5058 continue;
5059
Anders Carlssondee9a302009-11-17 04:44:12 +00005060 QualType FieldType = Context.getBaseElementType(Field->getType());
5061
5062 const RecordType* RT = FieldType->getAs<RecordType>();
5063 if (!RT)
5064 continue;
5065
5066 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005067 if (FieldClassDecl->isInvalidDecl())
5068 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005069 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005070 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005071 // The destructor for an implicit anonymous union member is never invoked.
5072 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5073 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005074
Douglas Gregore71edda2010-07-01 22:47:18 +00005075 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005076 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005077 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005078 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005079 << Field->getDeclName()
5080 << FieldType);
5081
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005082 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005083 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005084 }
5085
John McCall1064d7e2010-03-16 05:22:47 +00005086 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5087
Anders Carlssondee9a302009-11-17 04:44:12 +00005088 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005089 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005090 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005091 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005092
5093 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005094 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00005095 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00005096
John McCall1064d7e2010-03-16 05:22:47 +00005097 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005098 // If our base class is invalid, we probably can't get its dtor anyway.
5099 if (BaseClassDecl->isInvalidDecl())
5100 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005101 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005102 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005103
Douglas Gregore71edda2010-07-01 22:47:18 +00005104 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005105 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005106
5107 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005108 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005109 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005110 << Base.getType()
5111 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005112 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005113
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005114 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005115 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005116 }
5117
5118 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005119 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005120 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005121 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005122
5123 // Ignore direct virtual bases.
5124 if (DirectVirtualBases.count(RT))
5125 continue;
5126
John McCall1064d7e2010-03-16 05:22:47 +00005127 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005128 // If our base class is invalid, we probably can't get its dtor anyway.
5129 if (BaseClassDecl->isInvalidDecl())
5130 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005131 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005132 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005133
Douglas Gregore71edda2010-07-01 22:47:18 +00005134 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005135 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005136 if (CheckDestructorAccess(
5137 ClassDecl->getLocation(), Dtor,
5138 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005139 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005140 Context.getTypeDeclType(ClassDecl)) ==
5141 AR_accessible) {
5142 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005143 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005144 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005145 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005146 }
John McCall1064d7e2010-03-16 05:22:47 +00005147
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005148 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005149 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005150 }
5151}
5152
John McCall48871652010-08-21 09:40:31 +00005153void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005154 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005155 return;
Mike Stump11289f42009-09-09 15:08:12 +00005156
Mike Stump11289f42009-09-09 15:08:12 +00005157 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005158 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005159 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005160 DiagnoseUninitializedFields(*this, Constructor);
5161 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005162}
5163
Richard Smithdb0ac552015-12-18 22:40:25 +00005164bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005165 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005166 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005167
Richard Smithdb0ac552015-12-18 22:40:25 +00005168 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5169 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005170 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005171
Richard Smithdb0ac552015-12-18 22:40:25 +00005172 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5173 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005174
John McCall02db245d2010-08-18 09:41:07 +00005175 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005176 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005177 // over all the declarations when we have a full definition.
5178 const CXXRecordDecl *Def = RD->getDefinition();
5179 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005180 return false;
5181
Richard Smithdb0ac552015-12-18 22:40:25 +00005182 return RD->isAbstract();
5183}
5184
5185bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5186 TypeDiagnoser &Diagnoser) {
5187 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005188 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005189
Richard Smithdb0ac552015-12-18 22:40:25 +00005190 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005191 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005192 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005193 return true;
5194}
5195
5196void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5197 // Check if we've already emitted the list of pure virtual functions
5198 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005199 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005200 return;
Mike Stump11289f42009-09-09 15:08:12 +00005201
Richard Smithbc46e432013-07-22 02:56:56 +00005202 // If the diagnostic is suppressed, don't emit the notes. We're only
5203 // going to emit them once, so try to attach them to a diagnostic we're
5204 // actually going to show.
5205 if (Diags.isLastDiagnosticIgnored())
5206 return;
5207
Douglas Gregor4165bd62010-03-23 23:47:56 +00005208 CXXFinalOverriderMap FinalOverriders;
5209 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005210
Anders Carlssona2f74f32010-06-03 01:00:02 +00005211 // Keep a set of seen pure methods so we won't diagnose the same method
5212 // more than once.
5213 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5214
Douglas Gregor4165bd62010-03-23 23:47:56 +00005215 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5216 MEnd = FinalOverriders.end();
5217 M != MEnd;
5218 ++M) {
5219 for (OverridingMethods::iterator SO = M->second.begin(),
5220 SOEnd = M->second.end();
5221 SO != SOEnd; ++SO) {
5222 // C++ [class.abstract]p4:
5223 // A class is abstract if it contains or inherits at least one
5224 // pure virtual function for which the final overrider is pure
5225 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005226
Douglas Gregor4165bd62010-03-23 23:47:56 +00005227 //
5228 if (SO->second.size() != 1)
5229 continue;
5230
5231 if (!SO->second.front().Method->isPure())
5232 continue;
5233
David Blaikie82e95a32014-11-19 07:49:47 +00005234 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005235 continue;
5236
Douglas Gregor4165bd62010-03-23 23:47:56 +00005237 Diag(SO->second.front().Method->getLocation(),
5238 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005239 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005240 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005241 }
5242
5243 if (!PureVirtualClassDiagSet)
5244 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5245 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005246}
5247
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005248namespace {
John McCall02db245d2010-08-18 09:41:07 +00005249struct AbstractUsageInfo {
5250 Sema &S;
5251 CXXRecordDecl *Record;
5252 CanQualType AbstractType;
5253 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005254
John McCall02db245d2010-08-18 09:41:07 +00005255 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5256 : S(S), Record(Record),
5257 AbstractType(S.Context.getCanonicalType(
5258 S.Context.getTypeDeclType(Record))),
5259 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005260
John McCall02db245d2010-08-18 09:41:07 +00005261 void DiagnoseAbstractType() {
5262 if (Invalid) return;
5263 S.DiagnoseAbstractType(Record);
5264 Invalid = true;
5265 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005266
John McCall02db245d2010-08-18 09:41:07 +00005267 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5268};
5269
5270struct CheckAbstractUsage {
5271 AbstractUsageInfo &Info;
5272 const NamedDecl *Ctx;
5273
5274 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5275 : Info(Info), Ctx(Ctx) {}
5276
5277 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5278 switch (TL.getTypeLocClass()) {
5279#define ABSTRACT_TYPELOC(CLASS, PARENT)
5280#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005281 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005282#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005283 }
John McCall02db245d2010-08-18 09:41:07 +00005284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
John McCall02db245d2010-08-18 09:41:07 +00005286 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005287 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005288 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5289 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005290 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005291
5292 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005293 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005294 }
John McCall02db245d2010-08-18 09:41:07 +00005295 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005296
John McCall02db245d2010-08-18 09:41:07 +00005297 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5298 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5299 }
Mike Stump11289f42009-09-09 15:08:12 +00005300
John McCall02db245d2010-08-18 09:41:07 +00005301 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5302 // Visit the type parameters from a permissive context.
5303 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5304 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5305 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5306 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5307 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5308 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005309 }
John McCall02db245d2010-08-18 09:41:07 +00005310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311
John McCall02db245d2010-08-18 09:41:07 +00005312 // Visit pointee types from a permissive context.
5313#define CheckPolymorphic(Type) \
5314 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5315 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5316 }
5317 CheckPolymorphic(PointerTypeLoc)
5318 CheckPolymorphic(ReferenceTypeLoc)
5319 CheckPolymorphic(MemberPointerTypeLoc)
5320 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005321 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005322
John McCall02db245d2010-08-18 09:41:07 +00005323 /// Handle all the types we haven't given a more specific
5324 /// implementation for above.
5325 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5326 // Every other kind of type that we haven't called out already
5327 // that has an inner type is either (1) sugar or (2) contains that
5328 // inner type in some way as a subobject.
5329 if (TypeLoc Next = TL.getNextTypeLoc())
5330 return Visit(Next, Sel);
5331
5332 // If there's no inner type and we're in a permissive context,
5333 // don't diagnose.
5334 if (Sel == Sema::AbstractNone) return;
5335
5336 // Check whether the type matches the abstract type.
5337 QualType T = TL.getType();
5338 if (T->isArrayType()) {
5339 Sel = Sema::AbstractArrayType;
5340 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005341 }
John McCall02db245d2010-08-18 09:41:07 +00005342 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5343 if (CT != Info.AbstractType) return;
5344
5345 // It matched; do some magic.
5346 if (Sel == Sema::AbstractArrayType) {
5347 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5348 << T << TL.getSourceRange();
5349 } else {
5350 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5351 << Sel << T << TL.getSourceRange();
5352 }
5353 Info.DiagnoseAbstractType();
5354 }
5355};
5356
5357void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5358 Sema::AbstractDiagSelID Sel) {
5359 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5360}
5361
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005362}
John McCall02db245d2010-08-18 09:41:07 +00005363
5364/// Check for invalid uses of an abstract type in a method declaration.
5365static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5366 CXXMethodDecl *MD) {
5367 // No need to do the check on definitions, which require that
5368 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005369 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005370 return;
5371
5372 // For safety's sake, just ignore it if we don't have type source
5373 // information. This should never happen for non-implicit methods,
5374 // but...
5375 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5376 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5377}
5378
5379/// Check for invalid uses of an abstract type within a class definition.
5380static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5381 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005382 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005383 if (D->isImplicit()) continue;
5384
5385 // Methods and method templates.
5386 if (isa<CXXMethodDecl>(D)) {
5387 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5388 } else if (isa<FunctionTemplateDecl>(D)) {
5389 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5391
5392 // Fields and static variables.
5393 } else if (isa<FieldDecl>(D)) {
5394 FieldDecl *FD = cast<FieldDecl>(D);
5395 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5396 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5397 } else if (isa<VarDecl>(D)) {
5398 VarDecl *VD = cast<VarDecl>(D);
5399 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5400 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5401
5402 // Nested classes and class templates.
5403 } else if (isa<CXXRecordDecl>(D)) {
5404 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5405 } else if (isa<ClassTemplateDecl>(D)) {
5406 CheckAbstractClassUsage(Info,
5407 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5408 }
5409 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005410}
5411
Hans Wennborg99000c22015-08-15 01:18:16 +00005412static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5413 Attr *ClassAttr = getDLLAttr(Class);
5414 if (!ClassAttr)
5415 return;
5416
5417 assert(ClassAttr->getKind() == attr::DLLExport);
5418
5419 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5420
5421 if (TSK == TSK_ExplicitInstantiationDeclaration)
5422 // Don't go any further if this is just an explicit instantiation
5423 // declaration.
5424 return;
5425
5426 for (Decl *Member : Class->decls()) {
5427 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5428 if (!MD)
5429 continue;
5430
5431 if (Member->getAttr<DLLExportAttr>()) {
5432 if (MD->isUserProvided()) {
5433 // Instantiate non-default class member functions ...
5434
5435 // .. except for certain kinds of template specializations.
5436 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5437 continue;
5438
5439 S.MarkFunctionReferenced(Class->getLocation(), MD);
5440
5441 // The function will be passed to the consumer when its definition is
5442 // encountered.
5443 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5444 MD->isCopyAssignmentOperator() ||
5445 MD->isMoveAssignmentOperator()) {
5446 // Synthesize and instantiate non-trivial implicit methods, explicitly
5447 // defaulted methods, and the copy and move assignment operators. The
5448 // latter are exported even if they are trivial, because the address of
5449 // an operator can be taken and should compare equal accross libraries.
5450 DiagnosticErrorTrap Trap(S.Diags);
5451 S.MarkFunctionReferenced(Class->getLocation(), MD);
5452 if (Trap.hasErrorOccurred()) {
5453 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5454 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5455 break;
5456 }
5457
5458 // There is no later point when we will see the definition of this
5459 // function, so pass it to the consumer now.
5460 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5461 }
5462 }
5463 }
5464}
5465
Hans Wennborg853ae942014-05-30 16:59:42 +00005466/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005467void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005468 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005469
5470 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005471 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005472 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5473 if (Attr *TemplateAttr =
5474 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005475 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005476 A->setInherited(true);
5477 ClassAttr = A;
5478 }
5479 }
5480 }
5481
Hans Wennborg853ae942014-05-30 16:59:42 +00005482 if (!ClassAttr)
5483 return;
5484
Hans Wennborg8313c762014-11-03 16:09:16 +00005485 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005486 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005487 << Class << ClassAttr;
5488 return;
5489 }
5490
Hans Wennborg17f9b442015-05-27 00:06:45 +00005491 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005492 !ClassAttr->isInherited()) {
5493 // Diagnose dll attributes on members of class with dll attribute.
5494 for (Decl *Member : Class->decls()) {
5495 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5496 continue;
5497 InheritableAttr *MemberAttr = getDLLAttr(Member);
5498 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5499 continue;
5500
Hans Wennborg17f9b442015-05-27 00:06:45 +00005501 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005502 diag::err_attribute_dll_member_of_dll_class)
5503 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005504 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005505 Member->setInvalidDecl();
5506 }
5507 }
5508
5509 if (Class->getDescribedClassTemplate())
5510 // Don't inherit dll attribute until the template is instantiated.
5511 return;
5512
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005513 // The class is either imported or exported.
5514 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005515
Hans Wennborgfd76d912015-01-15 21:18:30 +00005516 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5517
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005518 // Ignore explicit dllexport on explicit class template instantiation declarations.
5519 if (ClassExported && !ClassAttr->isInherited() &&
5520 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005521 Class->dropAttr<DLLExportAttr>();
5522 return;
5523 }
5524
Hans Wennborg853ae942014-05-30 16:59:42 +00005525 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005526 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005527
5528 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5529 // seem to be true in practice?
5530
Hans Wennborg853ae942014-05-30 16:59:42 +00005531 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005532 VarDecl *VD = dyn_cast<VarDecl>(Member);
5533 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5534
5535 // Only methods and static fields inherit the attributes.
5536 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005537 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005538
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005539 if (MD) {
5540 // Don't process deleted methods.
5541 if (MD->isDeleted())
5542 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005543
David Majnemer30f058a2015-05-11 03:00:22 +00005544 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005545 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005546 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5547 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005548 continue;
5549
Dmitry Polukhin41581522016-05-13 09:03:56 +00005550 // MSVC versions before 2015 don't export the move assignment operators
5551 // and move constructor, so don't attempt to import/export them if
5552 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005553 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005554 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005555 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005556 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005557 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005558
5559 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5560 // operator is exported anyway.
5561 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5562 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5563 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005564 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005565 }
5566
Hans Wennborg287231c2015-04-22 04:05:17 +00005567 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5568 continue;
5569
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005570 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005571 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005572 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005573 NewAttr->setInherited(true);
5574 Member->addAttr(NewAttr);
5575 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005576 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005577
5578 if (ClassExported)
5579 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005580}
5581
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005582/// \brief Perform propagation of DLL attributes from a derived class to a
5583/// templated base class for MS compatibility.
5584void Sema::propagateDLLAttrToBaseClassTemplate(
5585 CXXRecordDecl *Class, Attr *ClassAttr,
5586 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5587 if (getDLLAttr(
5588 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5589 // If the base class template has a DLL attribute, don't try to change it.
5590 return;
5591 }
5592
5593 auto TSK = BaseTemplateSpec->getSpecializationKind();
5594 if (!getDLLAttr(BaseTemplateSpec) &&
5595 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5596 TSK == TSK_ImplicitInstantiation)) {
5597 // The template hasn't been instantiated yet (or it has, but only as an
5598 // explicit instantiation declaration or implicit instantiation, which means
5599 // we haven't codegenned any members yet), so propagate the attribute.
5600 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5601 NewAttr->setInherited(true);
5602 BaseTemplateSpec->addAttr(NewAttr);
5603
5604 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5605 // needs to be run again to work see the new attribute. Otherwise this will
5606 // get run whenever the template is instantiated.
5607 if (TSK != TSK_Undeclared)
5608 checkClassLevelDLLAttribute(BaseTemplateSpec);
5609
5610 return;
5611 }
5612
5613 if (getDLLAttr(BaseTemplateSpec)) {
5614 // The template has already been specialized or instantiated with an
5615 // attribute, explicitly or through propagation. We should not try to change
5616 // it.
5617 return;
5618 }
5619
5620 // The template was previously instantiated or explicitly specialized without
5621 // a dll attribute, It's too late for us to add an attribute, so warn that
5622 // this is unsupported.
5623 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5624 << BaseTemplateSpec->isExplicitSpecialization();
5625 Diag(ClassAttr->getLocation(), diag::note_attribute);
5626 if (BaseTemplateSpec->isExplicitSpecialization()) {
5627 Diag(BaseTemplateSpec->getLocation(),
5628 diag::note_template_class_explicit_specialization_was_here)
5629 << BaseTemplateSpec;
5630 } else {
5631 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5632 diag::note_template_class_instantiation_was_here)
5633 << BaseTemplateSpec;
5634 }
5635}
5636
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005637static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5638 SourceLocation DefaultLoc) {
5639 switch (S.getSpecialMember(MD)) {
5640 case Sema::CXXDefaultConstructor:
5641 S.DefineImplicitDefaultConstructor(DefaultLoc,
5642 cast<CXXConstructorDecl>(MD));
5643 break;
5644 case Sema::CXXCopyConstructor:
5645 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5646 break;
5647 case Sema::CXXCopyAssignment:
5648 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5649 break;
5650 case Sema::CXXDestructor:
5651 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5652 break;
5653 case Sema::CXXMoveConstructor:
5654 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5655 break;
5656 case Sema::CXXMoveAssignment:
5657 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5658 break;
5659 case Sema::CXXInvalid:
5660 llvm_unreachable("Invalid special member.");
5661 }
5662}
5663
Douglas Gregorc99f1552009-12-03 18:33:45 +00005664/// \brief Perform semantic checks on a class definition that has been
5665/// completing, introducing implicitly-declared members, checking for
5666/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005667void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005668 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005669 return;
5670
John McCall02db245d2010-08-18 09:41:07 +00005671 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5672 AbstractUsageInfo Info(*this, Record);
5673 CheckAbstractClassUsage(Info, Record);
5674 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005675
5676 // If this is not an aggregate type and has no user-declared constructor,
5677 // complain about any non-static data members of reference or const scalar
5678 // type, since they will never get initializers.
5679 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005680 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5681 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005682 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005683 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005684 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005685 continue;
5686
Douglas Gregor454a5b62010-04-15 00:00:53 +00005687 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005688 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005689 if (!Complained) {
5690 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5691 << Record->getTagKind() << Record;
5692 Complained = true;
5693 }
5694
5695 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5696 << F->getType()->isReferenceType()
5697 << F->getDeclName();
5698 }
5699 }
5700 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005701
Douglas Gregor36c22a22010-10-15 13:21:21 +00005702 if (Record->getIdentifier()) {
5703 // C++ [class.mem]p13:
5704 // If T is the name of a class, then each of the following shall have a
5705 // name different from T:
5706 // - every member of every anonymous union that is a member of class T.
5707 //
5708 // C++ [class.mem]p14:
5709 // In addition, if class T has a user-declared constructor (12.1), every
5710 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005711 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5712 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5713 ++I) {
5714 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005715 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5716 isa<IndirectFieldDecl>(D)) {
5717 Diag(D->getLocation(), diag::err_member_name_of_class)
5718 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005719 break;
5720 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005721 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005722 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005723
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005724 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005725 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005726 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005727 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5728 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005729 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5730 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5731 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005732
David Majnemera5433082013-10-18 00:33:31 +00005733 if (Record->isAbstract()) {
5734 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5735 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5736 << FA->isSpelledAsSealed();
5737 DiagnoseAbstractType(Record);
5738 }
David Blaikie348df502012-09-21 03:21:07 +00005739 }
5740
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005741 bool HasMethodWithOverrideControl = false,
5742 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005743 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005744 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005745 // See if a method overloads virtual methods in a base
5746 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005747 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005748 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005749 if (M->hasAttr<OverrideAttr>())
5750 HasMethodWithOverrideControl = true;
5751 else if (M->size_overridden_methods() > 0)
5752 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005753 // Check whether the explicitly-defaulted special members are valid.
5754 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005755 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005756
5757 // For an explicitly defaulted or deleted special member, we defer
5758 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005759 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005760 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005761 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005762 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005763
5764 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005765 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005766 }
5767 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005768
5769 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5770 M->hasAttr<DLLExportAttr>()) {
5771 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5772 M->isTrivial() &&
5773 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5774 CSM == CXXDestructor))
5775 M->dropAttr<DLLExportAttr>();
5776
5777 if (M->hasAttr<DLLExportAttr>()) {
5778 DefineImplicitSpecialMember(*this, M, M->getLocation());
5779 ActOnFinishInlineFunctionDef(M);
5780 }
5781 }
Richard Smithbd305122012-12-11 01:14:52 +00005782 }
5783 }
5784
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005785 if (HasMethodWithOverrideControl &&
5786 HasOverridingMethodWithoutOverrideControl) {
5787 // At least one method has the 'override' control declared.
5788 // Diagnose all other overridden methods which do not have 'override' specified on them.
5789 for (auto *M : Record->methods())
5790 DiagnoseAbsenceOfOverrideControl(M);
5791 }
Sebastian Redl08905022011-02-05 19:23:19 +00005792
John McCall95833f32014-02-27 20:30:49 +00005793 // ms_struct is a request to use the same ABI rules as MSVC. Check
5794 // whether this class uses any C++ features that are implemented
5795 // completely differently in MSVC, and if so, emit a diagnostic.
5796 // That diagnostic defaults to an error, but we allow projects to
5797 // map it down to a warning (or ignore it). It's a fairly common
5798 // practice among users of the ms_struct pragma to mass-annotate
5799 // headers, sweeping up a bunch of types that the project doesn't
5800 // really rely on MSVC-compatible layout for. We must therefore
5801 // support "ms_struct except for C++ stuff" as a secondary ABI.
5802 if (Record->isMsStruct(Context) &&
5803 (Record->isPolymorphic() || Record->getNumBases())) {
5804 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005805 }
5806
Hans Wennborg17f9b442015-05-27 00:06:45 +00005807 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005808}
5809
Richard Smith41c35d62013-11-27 03:39:20 +00005810/// Look up the special member function that would be called by a special
5811/// member function for a subobject of class type.
5812///
5813/// \param Class The class type of the subobject.
5814/// \param CSM The kind of special member function.
5815/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5816/// \param ConstRHS True if this is a copy operation with a const object
5817/// on its RHS, that is, if the argument to the outer special member
5818/// function is 'const' and this is not a field marked 'mutable'.
5819static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5820 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5821 unsigned FieldQuals, bool ConstRHS) {
5822 unsigned LHSQuals = 0;
5823 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5824 LHSQuals = FieldQuals;
5825
5826 unsigned RHSQuals = FieldQuals;
5827 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5828 RHSQuals = 0;
5829 else if (ConstRHS)
5830 RHSQuals |= Qualifiers::Const;
5831
5832 return S.LookupSpecialMember(Class, CSM,
5833 RHSQuals & Qualifiers::Const,
5834 RHSQuals & Qualifiers::Volatile,
5835 false,
5836 LHSQuals & Qualifiers::Const,
5837 LHSQuals & Qualifiers::Volatile);
5838}
5839
Richard Smith80a47022016-06-29 01:10:27 +00005840class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005841 Sema &S;
5842 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005843
5844 /// A mapping from the base classes through which the constructor was
5845 /// inherited to the using shadow declaration in that base class (or a null
5846 /// pointer if the constructor was declared in that base class).
5847 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5848 InheritedFromBases;
5849
Richard Smith80a47022016-06-29 01:10:27 +00005850public:
Richard Smith5179eb72016-06-28 19:03:57 +00005851 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5852 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005853 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005854 bool DiagnosedMultipleConstructedBases = false;
5855 CXXRecordDecl *ConstructedBase = nullptr;
5856 UsingDecl *ConstructedBaseUsing = nullptr;
5857
5858 // Find the set of such base class subobjects and check that there's a
5859 // unique constructed subobject.
5860 for (auto *D : Shadow->redecls()) {
5861 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5862 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5863 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5864
5865 InheritedFromBases.insert(
5866 std::make_pair(DNominatedBase->getCanonicalDecl(),
5867 DShadow->getNominatedBaseClassShadowDecl()));
5868 if (DShadow->constructsVirtualBase())
5869 InheritedFromBases.insert(
5870 std::make_pair(DConstructedBase->getCanonicalDecl(),
5871 DShadow->getConstructedBaseClassShadowDecl()));
5872 else
5873 assert(DNominatedBase == DConstructedBase);
5874
5875 // [class.inhctor.init]p2:
5876 // If the constructor was inherited from multiple base class subobjects
5877 // of type B, the program is ill-formed.
5878 if (!ConstructedBase) {
5879 ConstructedBase = DConstructedBase;
5880 ConstructedBaseUsing = D->getUsingDecl();
5881 } else if (ConstructedBase != DConstructedBase &&
5882 !Shadow->isInvalidDecl()) {
5883 if (!DiagnosedMultipleConstructedBases) {
5884 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5885 << Shadow->getTargetDecl();
5886 S.Diag(ConstructedBaseUsing->getLocation(),
5887 diag::note_ambiguous_inherited_constructor_using)
5888 << ConstructedBase;
5889 DiagnosedMultipleConstructedBases = true;
5890 }
5891 S.Diag(D->getUsingDecl()->getLocation(),
5892 diag::note_ambiguous_inherited_constructor_using)
5893 << DConstructedBase;
5894 }
5895 }
5896
5897 if (DiagnosedMultipleConstructedBases)
5898 Shadow->setInvalidDecl();
5899 }
5900
5901 /// Find the constructor to use for inherited construction of a base class,
5902 /// and whether that base class constructor inherits the constructor from a
5903 /// virtual base class (in which case it won't actually invoke it).
5904 std::pair<CXXConstructorDecl *, bool>
5905 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5906 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5907 if (It == InheritedFromBases.end())
5908 return std::make_pair(nullptr, false);
5909
5910 // This is an intermediary class.
5911 if (It->second)
5912 return std::make_pair(
5913 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5914 It->second->constructsVirtualBase());
5915
5916 // This is the base class from which the constructor was inherited.
5917 return std::make_pair(Ctor, false);
5918 }
5919};
Richard Smith5179eb72016-06-28 19:03:57 +00005920
Richard Smithb5800092012-06-10 05:43:50 +00005921/// Is the special member function which would be selected to perform the
5922/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005923static bool
5924specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5925 Sema::CXXSpecialMember CSM, unsigned Quals,
5926 bool ConstRHS,
5927 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005928 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005929 // If we're inheriting a constructor, see if we need to call it for this base
5930 // class.
5931 if (InheritedCtor) {
5932 assert(CSM == Sema::CXXDefaultConstructor);
5933 auto BaseCtor =
5934 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5935 if (BaseCtor)
5936 return BaseCtor->isConstexpr();
5937 }
5938
5939 if (CSM == Sema::CXXDefaultConstructor)
5940 return ClassDecl->hasConstexprDefaultConstructor();
5941
Richard Smithb5800092012-06-10 05:43:50 +00005942 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005943 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005944 if (!SMOR || !SMOR->getMethod())
5945 // A constructor we wouldn't select can't be "involved in initializing"
5946 // anything.
5947 return true;
5948 return SMOR->getMethod()->isConstexpr();
5949}
5950
5951/// Determine whether the specified special member function would be constexpr
5952/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005953static bool defaultedSpecialMemberIsConstexpr(
5954 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5955 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005956 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005957 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005958 return false;
5959
5960 // C++11 [dcl.constexpr]p4:
5961 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005962 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005963 switch (CSM) {
5964 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00005965 if (Inherited)
5966 break;
Richard Smith4086a132012-06-10 07:07:24 +00005967 // Since default constructor lookup is essentially trivial (and cannot
5968 // involve, for instance, template instantiation), we compute whether a
5969 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5970 //
5971 // This is important for performance; we need to know whether the default
5972 // constructor is constexpr to determine whether the type is a literal type.
5973 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5974
Richard Smithb5800092012-06-10 05:43:50 +00005975 case Sema::CXXCopyConstructor:
5976 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005977 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005978 break;
5979
5980 case Sema::CXXCopyAssignment:
5981 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005982 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005983 return false;
5984 // In C++1y, we need to perform overload resolution.
5985 Ctor = false;
5986 break;
5987
Richard Smithb5800092012-06-10 05:43:50 +00005988 case Sema::CXXDestructor:
5989 case Sema::CXXInvalid:
5990 return false;
5991 }
5992
5993 // -- if the class is a non-empty union, or for each non-empty anonymous
5994 // union member of a non-union class, exactly one non-static data member
5995 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005996 //
5997 // If we squint, this is guaranteed, since exactly one non-static data member
5998 // will be initialized (if the constructor isn't deleted), we just don't know
5999 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006000 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006001 return CSM == Sema::CXXDefaultConstructor
6002 ? ClassDecl->hasInClassInitializer() ||
6003 !ClassDecl->hasVariantMembers()
6004 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006005
6006 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006007 if (Ctor && ClassDecl->getNumVBases())
6008 return false;
6009
6010 // C++1y [class.copy]p26:
6011 // -- [the class] is a literal type, and
6012 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006013 return false;
6014
6015 // -- every constructor involved in initializing [...] base class
6016 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006017 // -- the assignment operator selected to copy/move each direct base
6018 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006019 for (const auto &B : ClassDecl->bases()) {
6020 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006021 if (!BaseType) continue;
6022
6023 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006024 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6025 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006026 return false;
6027 }
6028
6029 // -- every constructor involved in initializing non-static data members
6030 // [...] shall be a constexpr constructor;
6031 // -- every non-static data member and base class sub-object shall be
6032 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006033 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006034 // thereof), the assignment operator selected to copy/move that member is
6035 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006036 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006037 if (F->isInvalidDecl())
6038 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006039 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6040 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006041 QualType BaseType = S.Context.getBaseElementType(F->getType());
6042 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006043 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006044 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6045 BaseType.getCVRQualifiers(),
6046 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006047 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006048 } else if (CSM == Sema::CXXDefaultConstructor) {
6049 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006050 }
6051 }
6052
6053 // All OK, it's constexpr!
6054 return true;
6055}
6056
Richard Smithd3b5c9082012-07-27 04:22:15 +00006057static Sema::ImplicitExceptionSpecification
6058computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6059 switch (S.getSpecialMember(MD)) {
6060 case Sema::CXXDefaultConstructor:
6061 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6062 case Sema::CXXCopyConstructor:
6063 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6064 case Sema::CXXCopyAssignment:
6065 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6066 case Sema::CXXMoveConstructor:
6067 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6068 case Sema::CXXMoveAssignment:
6069 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6070 case Sema::CXXDestructor:
6071 return S.ComputeDefaultedDtorExceptionSpec(MD);
6072 case Sema::CXXInvalid:
6073 break;
6074 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00006075 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6076 "only special members have implicit exception specs");
Richard Smith5179eb72016-06-28 19:03:57 +00006077 return S.ComputeInheritingCtorExceptionSpec(Loc,
6078 cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00006079}
6080
Reid Kleckner78af0702013-08-27 23:08:25 +00006081static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6082 CXXMethodDecl *MD) {
6083 FunctionProtoType::ExtProtoInfo EPI;
6084
6085 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006086 EPI.ExceptionSpec.Type = EST_Unevaluated;
6087 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006088
6089 // Set the calling convention to the default for C++ instance methods.
6090 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6091 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6092 /*IsCXXMethod=*/true));
6093 return EPI;
6094}
6095
Richard Smithd3b5c9082012-07-27 04:22:15 +00006096void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6097 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6098 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6099 return;
6100
Richard Smith7f782272012-07-30 23:48:14 +00006101 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00006102 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006103
Richard Smith7f782272012-07-30 23:48:14 +00006104 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006105 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006106
6107 // A user-provided destructor can be defined outside the class. When that
6108 // happens, be sure to update the exception specification on both
6109 // declarations.
6110 const FunctionProtoType *CanonicalFPT =
6111 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6112 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006113 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006114}
6115
Richard Smithb9e90b12012-05-15 04:39:51 +00006116void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6117 CXXRecordDecl *RD = MD->getParent();
6118 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006119
Richard Smithb9e90b12012-05-15 04:39:51 +00006120 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6121 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006122
6123 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006124 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006125 bool First = MD == MD->getCanonicalDecl();
6126
6127 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006128
6129 // C++11 [dcl.fct.def.default]p1:
6130 // A function that is explicitly defaulted shall
6131 // -- be a special member function (checked elsewhere),
6132 // -- have the same type (except for ref-qualifiers, and except that a
6133 // copy operation can take a non-const reference) as an implicit
6134 // declaration, and
6135 // -- not have default arguments.
6136 unsigned ExpectedParams = 1;
6137 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6138 ExpectedParams = 0;
6139 if (MD->getNumParams() != ExpectedParams) {
6140 // This also checks for default arguments: a copy or move constructor with a
6141 // default argument is classified as a default constructor, and assignment
6142 // operations and destructors can't have default arguments.
6143 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6144 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006145 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006146 } else if (MD->isVariadic()) {
6147 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6148 << CSM << MD->getSourceRange();
6149 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006150 }
6151
Richard Smithb9e90b12012-05-15 04:39:51 +00006152 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006153
Richard Smithb5800092012-06-10 05:43:50 +00006154 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006155 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006156 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006157 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006158 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006159
Richard Smithb9e90b12012-05-15 04:39:51 +00006160 QualType ReturnType = Context.VoidTy;
6161 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6162 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006163 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006164 QualType ExpectedReturnType =
6165 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6166 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6167 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6168 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6169 HadError = true;
6170 }
6171
6172 // A defaulted special member cannot have cv-qualifiers.
6173 if (Type->getTypeQuals()) {
6174 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006175 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006176 HadError = true;
6177 }
6178 }
6179
6180 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006181 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006182 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006183 if (ExpectedParams && ArgType->isReferenceType()) {
6184 // Argument must be reference to possibly-const T.
6185 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006186 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006187
6188 if (ReferentType.isVolatileQualified()) {
6189 Diag(MD->getLocation(),
6190 diag::err_defaulted_special_member_volatile_param) << CSM;
6191 HadError = true;
6192 }
6193
Richard Smithb5800092012-06-10 05:43:50 +00006194 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006195 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6196 Diag(MD->getLocation(),
6197 diag::err_defaulted_special_member_copy_const_param)
6198 << (CSM == CXXCopyAssignment);
6199 // FIXME: Explain why this special member can't be const.
6200 } else {
6201 Diag(MD->getLocation(),
6202 diag::err_defaulted_special_member_move_const_param)
6203 << (CSM == CXXMoveAssignment);
6204 }
6205 HadError = true;
6206 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006207 } else if (ExpectedParams) {
6208 // A copy assignment operator can take its argument by value, but a
6209 // defaulted one cannot.
6210 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006211 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006212 HadError = true;
6213 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006214
Richard Smithcc36f692011-12-22 02:22:31 +00006215 // C++11 [dcl.fct.def.default]p2:
6216 // An explicitly-defaulted function may be declared constexpr only if it
6217 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006218 // Do not apply this rule to members of class templates, since core issue 1358
6219 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006220 // functions which cannot be constexpr (for non-constructors in C++11 and for
6221 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006222 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6223 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006224 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006225 : isa<CXXConstructorDecl>(MD)) &&
6226 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006227 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6228 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006229 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006230 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006231 }
Richard Smithbd305122012-12-11 01:14:52 +00006232
Richard Smithcc36f692011-12-22 02:22:31 +00006233 // and may have an explicit exception-specification only if it is compatible
6234 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006235 if (Type->hasExceptionSpec()) {
6236 // Delay the check if this is the first declaration of the special member,
6237 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006238 if (First) {
6239 // If the exception specification needs to be instantiated, do so now,
6240 // before we clobber it with an EST_Unevaluated specification below.
6241 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6242 InstantiateExceptionSpec(MD->getLocStart(), MD);
6243 Type = MD->getType()->getAs<FunctionProtoType>();
6244 }
Richard Smithbd305122012-12-11 01:14:52 +00006245 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006246 } else
Richard Smithbd305122012-12-11 01:14:52 +00006247 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6248 }
Richard Smithcc36f692011-12-22 02:22:31 +00006249
6250 // If a function is explicitly defaulted on its first declaration,
6251 if (First) {
6252 // -- it is implicitly considered to be constexpr if the implicit
6253 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006254 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006255
Richard Smithb9e90b12012-05-15 04:39:51 +00006256 // -- it is implicitly considered to have the same exception-specification
6257 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006258 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006259 EPI.ExceptionSpec.Type = EST_Unevaluated;
6260 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006261 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006262 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006263 ExpectedParams),
6264 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006265 }
6266
Richard Smithb9e90b12012-05-15 04:39:51 +00006267 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006268 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006269 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006270 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006271 // C++11 [dcl.fct.def.default]p4:
6272 // [For a] user-provided explicitly-defaulted function [...] if such a
6273 // function is implicitly defined as deleted, the program is ill-formed.
6274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006275 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006276 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006277 }
6278 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006279
Richard Smithb9e90b12012-05-15 04:39:51 +00006280 if (HadError)
6281 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006282}
6283
Richard Smithbd305122012-12-11 01:14:52 +00006284/// Check whether the exception specification provided for an
6285/// explicitly-defaulted special member matches the exception specification
6286/// that would have been generated for an implicit special member, per
6287/// C++11 [dcl.fct.def.default]p2.
6288void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6289 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006290 // If the exception specification was explicitly specified but hadn't been
6291 // parsed when the method was defaulted, grab it now.
6292 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6293 SpecifiedType =
6294 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6295
Richard Smithbd305122012-12-11 01:14:52 +00006296 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006297 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6298 /*IsCXXMethod=*/true);
6299 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00006300 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6301 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006302 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006303 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006304
6305 // Ensure that it matches.
6306 CheckEquivalentExceptionSpec(
6307 PDiag(diag::err_incorrect_defaulted_exception_spec)
6308 << getSpecialMember(MD), PDiag(),
6309 ImplicitType, SourceLocation(),
6310 SpecifiedType, MD->getLocation());
6311}
6312
Alp Tokerae3a9442013-10-18 05:54:19 +00006313void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006314 decltype(DelayedExceptionSpecChecks) Checks;
6315 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006316
Richard Smith88f45492014-11-22 03:09:05 +00006317 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006318 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6319
6320 // Perform any deferred checking of exception specifications for virtual
6321 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006322 for (auto &Check : Checks)
6323 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006324
6325 // Check that any explicitly-defaulted methods have exception specifications
6326 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006327 for (auto &Spec : Specs)
6328 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006329}
6330
Richard Smithd951a1d2012-02-18 02:02:13 +00006331namespace {
6332struct SpecialMemberDeletionInfo {
6333 Sema &S;
6334 CXXMethodDecl *MD;
6335 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006336 Sema::InheritedConstructorInfo *ICI;
Richard Smith852265f2012-03-30 20:53:28 +00006337 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006338
6339 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00006340 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00006341 SourceLocation Loc;
6342
6343 bool AllFieldsAreConst;
6344
6345 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006346 Sema::CXXSpecialMember CSM,
6347 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6348 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6349 IsConstructor(false), IsAssignment(false), IsMove(false),
6350 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006351 switch (CSM) {
6352 case Sema::CXXDefaultConstructor:
6353 case Sema::CXXCopyConstructor:
6354 IsConstructor = true;
6355 break;
6356 case Sema::CXXMoveConstructor:
6357 IsConstructor = true;
6358 IsMove = true;
6359 break;
6360 case Sema::CXXCopyAssignment:
6361 IsAssignment = true;
6362 break;
6363 case Sema::CXXMoveAssignment:
6364 IsAssignment = true;
6365 IsMove = true;
6366 break;
6367 case Sema::CXXDestructor:
6368 break;
6369 case Sema::CXXInvalid:
6370 llvm_unreachable("invalid special member kind");
6371 }
6372
6373 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00006374 if (const ReferenceType *RT =
6375 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6376 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00006377 }
6378 }
6379
6380 bool inUnion() const { return MD->getParent()->isUnion(); }
6381
Richard Smith80a47022016-06-29 01:10:27 +00006382 Sema::CXXSpecialMember getEffectiveCSM() {
6383 return ICI ? Sema::CXXInvalid : CSM;
6384 }
6385
Richard Smithd951a1d2012-02-18 02:02:13 +00006386 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00006387 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00006388 unsigned Quals, bool IsMutable) {
6389 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6390 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00006391 }
6392
Richard Smith852265f2012-03-30 20:53:28 +00006393 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00006394
Richard Smith852265f2012-03-30 20:53:28 +00006395 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006396 bool shouldDeleteForField(FieldDecl *FD);
6397 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006398
Richard Smithaf136f82012-07-18 03:51:16 +00006399 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6400 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006401 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6402 Sema::SpecialMemberOverloadResult *SMOR,
6403 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006404
6405 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006406};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006407}
Richard Smithd951a1d2012-02-18 02:02:13 +00006408
John McCalld4274212012-04-09 20:53:23 +00006409/// Is the given special member inaccessible when used on the given
6410/// sub-object.
6411bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6412 CXXMethodDecl *target) {
6413 /// If we're operating on a base class, the object type is the
6414 /// type of this special member.
6415 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006416 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006417 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6418 objectTy = S.Context.getTypeDeclType(MD->getParent());
6419 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6420
6421 // If we're operating on a field, the object type is the type of the field.
6422 } else {
6423 objectTy = S.Context.getTypeDeclType(target->getParent());
6424 }
6425
6426 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6427}
6428
Richard Smith852265f2012-03-30 20:53:28 +00006429/// Check whether we should delete a special member due to the implicit
6430/// definition containing a call to a special member of a subobject.
6431bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6432 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6433 bool IsDtorCallInCtor) {
6434 CXXMethodDecl *Decl = SMOR->getMethod();
6435 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6436
6437 int DiagKind = -1;
6438
6439 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6440 DiagKind = !Decl ? 0 : 1;
6441 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6442 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006443 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006444 DiagKind = 3;
6445 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6446 !Decl->isTrivial()) {
6447 // A member of a union must have a trivial corresponding special member.
6448 // As a weird special case, a destructor call from a union's constructor
6449 // must be accessible and non-deleted, but need not be trivial. Such a
6450 // destructor is never actually called, but is semantically checked as
6451 // if it were.
6452 DiagKind = 4;
6453 }
6454
6455 if (DiagKind == -1)
6456 return false;
6457
6458 if (Diagnose) {
6459 if (Field) {
6460 S.Diag(Field->getLocation(),
6461 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006462 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006463 << Field << DiagKind << IsDtorCallInCtor;
6464 } else {
6465 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6466 S.Diag(Base->getLocStart(),
6467 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006468 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006469 << Base->getType() << DiagKind << IsDtorCallInCtor;
6470 }
6471
6472 if (DiagKind == 1)
6473 S.NoteDeletedFunction(Decl);
6474 // FIXME: Explain inaccessibility if DiagKind == 3.
6475 }
6476
6477 return true;
6478}
6479
Richard Smith921bd202012-02-26 09:11:52 +00006480/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006481/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006482bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006483 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006484 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006485 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006486
6487 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006488 // -- any direct or virtual base class, or non-static data member with no
6489 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006490 // either M has no default constructor or overload resolution as applied
6491 // to M's default constructor results in an ambiguity or in a function
6492 // that is deleted or inaccessible
6493 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6494 // -- a direct or virtual base class B that cannot be copied/moved because
6495 // overload resolution, as applied to B's corresponding special member,
6496 // results in an ambiguity or a function that is deleted or inaccessible
6497 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006498 // C++11 [class.dtor]p5:
6499 // -- any direct or virtual base class [...] has a type with a destructor
6500 // that is deleted or inaccessible
6501 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006502 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006503 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6504 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006505 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006506
Richard Smith852265f2012-03-30 20:53:28 +00006507 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6508 // -- any direct or virtual base class or non-static data member has a
6509 // type with a destructor that is deleted or inaccessible
6510 if (IsConstructor) {
6511 Sema::SpecialMemberOverloadResult *SMOR =
6512 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6513 false, false, false, false, false);
6514 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6515 return true;
6516 }
6517
Richard Smith921bd202012-02-26 09:11:52 +00006518 return false;
6519}
6520
6521/// Check whether we should delete a special member function due to the class
6522/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006523bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006524 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006525 // If program is correct, BaseClass cannot be null, but if it is, the error
6526 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006527 if (!BaseClass)
6528 return false;
6529 // If we have an inheriting constructor, check whether we're calling an
6530 // inherited constructor instead of a default constructor.
6531 if (ICI) {
6532 assert(CSM == Sema::CXXDefaultConstructor);
6533 auto *BaseCtor =
6534 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6535 ->getInheritedConstructor()
6536 .getConstructor())
6537 .first;
6538 if (BaseCtor) {
6539 if (BaseCtor->isDeleted() && Diagnose) {
6540 S.Diag(Base->getLocStart(),
6541 diag::note_deleted_special_member_class_subobject)
6542 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6543 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6544 S.NoteDeletedFunction(BaseCtor);
6545 }
6546 return BaseCtor->isDeleted();
6547 }
6548 }
6549 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006550}
6551
6552/// Check whether we should delete a special member function due to the class
6553/// having a particular non-static data member.
6554bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6555 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6556 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6557
6558 if (CSM == Sema::CXXDefaultConstructor) {
6559 // For a default constructor, all references must be initialized in-class
6560 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006561 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6562 if (Diagnose)
6563 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006564 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006565 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006566 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006567 // C++11 [class.ctor]p5: any non-variant non-static data member of
6568 // const-qualified type (or array thereof) with no
6569 // brace-or-equal-initializer does not have a user-provided default
6570 // constructor.
6571 if (!inUnion() && FieldType.isConstQualified() &&
6572 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006573 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6574 if (Diagnose)
6575 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006576 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006577 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006578 }
6579
6580 if (inUnion() && !FieldType.isConstQualified())
6581 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006582 } else if (CSM == Sema::CXXCopyConstructor) {
6583 // For a copy constructor, data members must not be of rvalue reference
6584 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006585 if (FieldType->isRValueReferenceType()) {
6586 if (Diagnose)
6587 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6588 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006589 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006590 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006591 } else if (IsAssignment) {
6592 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006593 if (FieldType->isReferenceType()) {
6594 if (Diagnose)
6595 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6596 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006597 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006598 }
6599 if (!FieldRecord && FieldType.isConstQualified()) {
6600 // C++11 [class.copy]p23:
6601 // -- a non-static data member of const non-class type (or array thereof)
6602 if (Diagnose)
6603 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00006604 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006605 return true;
6606 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006607 }
6608
6609 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006610 // Some additional restrictions exist on the variant members.
6611 if (!inUnion() && FieldRecord->isUnion() &&
6612 FieldRecord->isAnonymousStructOrUnion()) {
6613 bool AllVariantFieldsAreConst = true;
6614
Richard Smith5704fe82012-03-29 19:00:10 +00006615 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006616 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006617 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006618
6619 if (!UnionFieldType.isConstQualified())
6620 AllVariantFieldsAreConst = false;
6621
Richard Smith921bd202012-02-26 09:11:52 +00006622 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6623 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006624 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006625 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006626 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006627 }
6628
6629 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006630 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006631 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006632 if (Diagnose)
6633 S.Diag(FieldRecord->getLocation(),
6634 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006635 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006636 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006637 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006638
Richard Smith5704fe82012-03-29 19:00:10 +00006639 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006640 // This is technically non-conformant, but sanity demands it.
6641 return false;
6642 }
6643
Richard Smithaf136f82012-07-18 03:51:16 +00006644 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6645 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006646 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006647 }
6648
6649 return false;
6650}
6651
6652/// C++11 [class.ctor] p5:
6653/// A defaulted default constructor for a class X is defined as deleted if
6654/// X is a union and all of its variant members are of const-qualified type.
6655bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006656 // This is a silly definition, because it gives an empty union a deleted
6657 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006658 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6659 bool AnyFields = false;
6660 for (auto *F : MD->getParent()->fields())
6661 if ((AnyFields = !F->isUnnamedBitfield()))
6662 break;
6663 if (!AnyFields)
6664 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006665 if (Diagnose)
6666 S.Diag(MD->getParent()->getLocation(),
6667 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006668 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006669 return true;
6670 }
6671 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006672}
6673
6674/// Determine whether a defaulted special member function should be defined as
6675/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6676/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006677bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006678 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006679 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006680 if (MD->isInvalidDecl())
6681 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006682 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006683 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006684 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006685 return false;
6686
Richard Smithd951a1d2012-02-18 02:02:13 +00006687 // C++11 [expr.lambda.prim]p19:
6688 // The closure type associated with a lambda-expression has a
6689 // deleted (8.4.3) default constructor and a deleted copy
6690 // assignment operator.
6691 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006692 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6693 if (Diagnose)
6694 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006695 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006696 }
6697
Richard Smith6f1e2c62012-04-02 20:59:25 +00006698 // For an anonymous struct or union, the copy and assignment special members
6699 // will never be used, so skip the check. For an anonymous union declared at
6700 // namespace scope, the constructor and destructor are used.
6701 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6702 RD->isAnonymousStructOrUnion())
6703 return false;
6704
Richard Smith852265f2012-03-30 20:53:28 +00006705 // C++11 [class.copy]p7, p18:
6706 // If the class definition declares a move constructor or move assignment
6707 // operator, an implicitly declared copy constructor or copy assignment
6708 // operator is defined as deleted.
6709 if (MD->isImplicit() &&
6710 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006711 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006712
6713 // In Microsoft mode, a user-declared move only causes the deletion of the
6714 // corresponding copy operation, not both copy operations.
6715 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00006716 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006717 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006718
6719 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006720 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006721 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006722 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006723 break;
6724 }
6725 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006726 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006727 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00006728 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006729 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006730
6731 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006732 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006733 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006734 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006735 break;
6736 }
6737 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006738 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006739 }
6740
6741 if (UserDeclaredMove) {
6742 Diag(UserDeclaredMove->getLocation(),
6743 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006744 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006745 << UserDeclaredMove->isMoveAssignmentOperator();
6746 return true;
6747 }
6748 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006749
Richard Smith6f1e2c62012-04-02 20:59:25 +00006750 // Do access control from the special member function
6751 ContextRAII MethodContext(*this, MD);
6752
Richard Smith921bd202012-02-26 09:11:52 +00006753 // C++11 [class.dtor]p5:
6754 // -- for a virtual destructor, lookup of the non-array deallocation function
6755 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006756 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006757 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006758 DeclarationName Name =
6759 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6760 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006761 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006762 if (Diagnose)
6763 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006764 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006765 }
Richard Smith921bd202012-02-26 09:11:52 +00006766 }
6767
Richard Smith80a47022016-06-29 01:10:27 +00006768 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006769
Aaron Ballman574705e2014-03-13 15:41:46 +00006770 for (auto &BI : RD->bases())
Richard Smith0786d5b2016-08-31 20:37:39 +00006771 if ((SMI.IsAssignment || !BI.isVirtual()) &&
Aaron Ballman574705e2014-03-13 15:41:46 +00006772 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00006773 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006774
Richard Smithd1627032013-07-22 18:06:23 +00006775 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smith0786d5b2016-08-31 20:37:39 +00006776 // classes, since we are not going to construct them. For assignment
6777 // operators, we only assign (and thus only consider) direct bases.
6778 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006779 for (auto &BI : RD->vbases())
6780 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00006781 return true;
6782 }
Alexis Huntea6f0322011-05-11 22:34:38 +00006783
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006784 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00006785 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006786 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00006787 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006788
Richard Smithd951a1d2012-02-18 02:02:13 +00006789 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006790 return true;
6791
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006792 if (getLangOpts().CUDA) {
6793 // We should delete the special member in CUDA mode if target inference
6794 // failed.
6795 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6796 Diagnose);
6797 }
6798
Alexis Huntea6f0322011-05-11 22:34:38 +00006799 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006800}
6801
Richard Smith92f241f2012-12-08 02:53:02 +00006802/// Perform lookup for a special member of the specified kind, and determine
6803/// whether it is trivial. If the triviality can be determined without the
6804/// lookup, skip it. This is intended for use when determining whether a
6805/// special member of a containing object is trivial, and thus does not ever
6806/// perform overload resolution for default constructors.
6807///
6808/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6809/// member that was most likely to be intended to be trivial, if any.
6810static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6811 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006812 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006813 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006814 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006815
6816 switch (CSM) {
6817 case Sema::CXXInvalid:
6818 llvm_unreachable("not a special member");
6819
6820 case Sema::CXXDefaultConstructor:
6821 // C++11 [class.ctor]p5:
6822 // A default constructor is trivial if:
6823 // - all the [direct subobjects] have trivial default constructors
6824 //
6825 // Note, no overload resolution is performed in this case.
6826 if (RD->hasTrivialDefaultConstructor())
6827 return true;
6828
6829 if (Selected) {
6830 // If there's a default constructor which could have been trivial, dig it
6831 // out. Otherwise, if there's any user-provided default constructor, point
6832 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006833 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006834 if (RD->needsImplicitDefaultConstructor())
6835 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006836 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006837 if (!CI->isDefaultConstructor())
6838 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006839 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006840 if (!DefCtor->isUserProvided())
6841 break;
6842 }
6843
6844 *Selected = DefCtor;
6845 }
6846
6847 return false;
6848
6849 case Sema::CXXDestructor:
6850 // C++11 [class.dtor]p5:
6851 // A destructor is trivial if:
6852 // - all the direct [subobjects] have trivial destructors
6853 if (RD->hasTrivialDestructor())
6854 return true;
6855
6856 if (Selected) {
6857 if (RD->needsImplicitDestructor())
6858 S.DeclareImplicitDestructor(RD);
6859 *Selected = RD->getDestructor();
6860 }
6861
6862 return false;
6863
6864 case Sema::CXXCopyConstructor:
6865 // C++11 [class.copy]p12:
6866 // A copy constructor is trivial if:
6867 // - the constructor selected to copy each direct [subobject] is trivial
6868 if (RD->hasTrivialCopyConstructor()) {
6869 if (Quals == Qualifiers::Const)
6870 // We must either select the trivial copy constructor or reach an
6871 // ambiguity; no need to actually perform overload resolution.
6872 return true;
6873 } else if (!Selected) {
6874 return false;
6875 }
6876 // In C++98, we are not supposed to perform overload resolution here, but we
6877 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6878 // cases like B as having a non-trivial copy constructor:
6879 // struct A { template<typename T> A(T&); };
6880 // struct B { mutable A a; };
6881 goto NeedOverloadResolution;
6882
6883 case Sema::CXXCopyAssignment:
6884 // C++11 [class.copy]p25:
6885 // A copy assignment operator is trivial if:
6886 // - the assignment operator selected to copy each direct [subobject] is
6887 // trivial
6888 if (RD->hasTrivialCopyAssignment()) {
6889 if (Quals == Qualifiers::Const)
6890 return true;
6891 } else if (!Selected) {
6892 return false;
6893 }
6894 // In C++98, we are not supposed to perform overload resolution here, but we
6895 // treat that as a language defect.
6896 goto NeedOverloadResolution;
6897
6898 case Sema::CXXMoveConstructor:
6899 case Sema::CXXMoveAssignment:
6900 NeedOverloadResolution:
6901 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006902 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006903
6904 // The standard doesn't describe how to behave if the lookup is ambiguous.
6905 // We treat it as not making the member non-trivial, just like the standard
6906 // mandates for the default constructor. This should rarely matter, because
6907 // the member will also be deleted.
6908 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6909 return true;
6910
6911 if (!SMOR->getMethod()) {
6912 assert(SMOR->getKind() ==
6913 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6914 return false;
6915 }
6916
6917 // We deliberately don't check if we found a deleted special member. We're
6918 // not supposed to!
6919 if (Selected)
6920 *Selected = SMOR->getMethod();
6921 return SMOR->getMethod()->isTrivial();
6922 }
6923
6924 llvm_unreachable("unknown special method kind");
6925}
6926
Benjamin Kramer3e350262013-02-15 12:30:38 +00006927static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006928 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006929 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006930 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006931
6932 // Look for constructor templates.
6933 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6934 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6935 if (CXXConstructorDecl *CD =
6936 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6937 return CD;
6938 }
6939
Craig Topperc3ec1492014-05-26 06:22:03 +00006940 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006941}
6942
6943/// The kind of subobject we are checking for triviality. The values of this
6944/// enumeration are used in diagnostics.
6945enum TrivialSubobjectKind {
6946 /// The subobject is a base class.
6947 TSK_BaseClass,
6948 /// The subobject is a non-static data member.
6949 TSK_Field,
6950 /// The object is actually the complete object.
6951 TSK_CompleteObject
6952};
6953
6954/// Check whether the special member selected for a given type would be trivial.
6955static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006956 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006957 Sema::CXXSpecialMember CSM,
6958 TrivialSubobjectKind Kind,
6959 bool Diagnose) {
6960 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6961 if (!SubRD)
6962 return true;
6963
6964 CXXMethodDecl *Selected;
6965 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006966 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006967 return true;
6968
6969 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006970 if (ConstRHS)
6971 SubType.addConst();
6972
Richard Smith92f241f2012-12-08 02:53:02 +00006973 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6974 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6975 << Kind << SubType.getUnqualifiedType();
6976 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6977 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6978 } else if (!Selected)
6979 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6980 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6981 else if (Selected->isUserProvided()) {
6982 if (Kind == TSK_CompleteObject)
6983 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6984 << Kind << SubType.getUnqualifiedType() << CSM;
6985 else {
6986 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6987 << Kind << SubType.getUnqualifiedType() << CSM;
6988 S.Diag(Selected->getLocation(), diag::note_declared_at);
6989 }
6990 } else {
6991 if (Kind != TSK_CompleteObject)
6992 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6993 << Kind << SubType.getUnqualifiedType() << CSM;
6994
6995 // Explain why the defaulted or deleted special member isn't trivial.
6996 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6997 }
6998 }
6999
7000 return false;
7001}
7002
7003/// Check whether the members of a class type allow a special member to be
7004/// trivial.
7005static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7006 Sema::CXXSpecialMember CSM,
7007 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007008 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007009 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7010 continue;
7011
7012 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7013
7014 // Pretend anonymous struct or union members are members of this class.
7015 if (FI->isAnonymousStructOrUnion()) {
7016 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7017 CSM, ConstArg, Diagnose))
7018 return false;
7019 continue;
7020 }
7021
7022 // C++11 [class.ctor]p5:
7023 // A default constructor is trivial if [...]
7024 // -- no non-static data member of its class has a
7025 // brace-or-equal-initializer
7026 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7027 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007028 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007029 return false;
7030 }
7031
7032 // Objective C ARC 4.3.5:
7033 // [...] nontrivally ownership-qualified types are [...] not trivially
7034 // default constructible, copy constructible, move constructible, copy
7035 // assignable, move assignable, or destructible [...]
7036 if (S.getLangOpts().ObjCAutoRefCount &&
7037 FieldType.hasNonTrivialObjCLifetime()) {
7038 if (Diagnose)
7039 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7040 << RD << FieldType.getObjCLifetime();
7041 return false;
7042 }
7043
Richard Smith41c35d62013-11-27 03:39:20 +00007044 bool ConstRHS = ConstArg && !FI->isMutable();
7045 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7046 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007047 return false;
7048 }
7049
7050 return true;
7051}
7052
7053/// Diagnose why the specified class does not have a trivial special member of
7054/// the given kind.
7055void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7056 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007057
Richard Smith41c35d62013-11-27 03:39:20 +00007058 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7059 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007060 TSK_CompleteObject, /*Diagnose*/true);
7061}
7062
7063/// Determine whether a defaulted or deleted special member function is trivial,
7064/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7065/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7066bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7067 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007068 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7069
7070 CXXRecordDecl *RD = MD->getParent();
7071
7072 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007073
Richard Smith2002bfe2013-11-04 02:02:27 +00007074 // C++11 [class.copy]p12, p25: [DR1593]
7075 // A [special member] is trivial if [...] its parameter-type-list is
7076 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007077 switch (CSM) {
7078 case CXXDefaultConstructor:
7079 case CXXDestructor:
7080 // Trivial default constructors and destructors cannot have parameters.
7081 break;
7082
7083 case CXXCopyConstructor:
7084 case CXXCopyAssignment: {
7085 // Trivial copy operations always have const, non-volatile parameter types.
7086 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007087 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007088 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7089 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7090 if (Diagnose)
7091 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7092 << Param0->getSourceRange() << Param0->getType()
7093 << Context.getLValueReferenceType(
7094 Context.getRecordType(RD).withConst());
7095 return false;
7096 }
7097 break;
7098 }
7099
7100 case CXXMoveConstructor:
7101 case CXXMoveAssignment: {
7102 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007103 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007104 const RValueReferenceType *RT =
7105 Param0->getType()->getAs<RValueReferenceType>();
7106 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7107 if (Diagnose)
7108 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7109 << Param0->getSourceRange() << Param0->getType()
7110 << Context.getRValueReferenceType(Context.getRecordType(RD));
7111 return false;
7112 }
7113 break;
7114 }
7115
7116 case CXXInvalid:
7117 llvm_unreachable("not a special member");
7118 }
7119
Richard Smith92f241f2012-12-08 02:53:02 +00007120 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7121 if (Diagnose)
7122 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7123 diag::note_nontrivial_default_arg)
7124 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7125 return false;
7126 }
7127 if (MD->isVariadic()) {
7128 if (Diagnose)
7129 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7130 return false;
7131 }
7132
7133 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7134 // A copy/move [constructor or assignment operator] is trivial if
7135 // -- the [member] selected to copy/move each direct base class subobject
7136 // is trivial
7137 //
7138 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7139 // A [default constructor or destructor] is trivial if
7140 // -- all the direct base classes have trivial [default constructors or
7141 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007142 for (const auto &BI : RD->bases())
7143 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007144 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007145 return false;
7146
7147 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7148 // A copy/move [constructor or assignment operator] for a class X is
7149 // trivial if
7150 // -- for each non-static data member of X that is of class type (or array
7151 // thereof), the constructor selected to copy/move that member is
7152 // trivial
7153 //
7154 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7155 // A [default constructor or destructor] is trivial if
7156 // -- for all of the non-static data members of its class that are of class
7157 // type (or array thereof), each such class has a trivial [default
7158 // constructor or destructor]
7159 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7160 return false;
7161
7162 // C++11 [class.dtor]p5:
7163 // A destructor is trivial if [...]
7164 // -- the destructor is not virtual
7165 if (CSM == CXXDestructor && MD->isVirtual()) {
7166 if (Diagnose)
7167 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7168 return false;
7169 }
7170
7171 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7172 // A [special member] for class X is trivial if [...]
7173 // -- class X has no virtual functions and no virtual base classes
7174 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7175 if (!Diagnose)
7176 return false;
7177
7178 if (RD->getNumVBases()) {
7179 // Check for virtual bases. We already know that the corresponding
7180 // member in all bases is trivial, so vbases must all be direct.
7181 CXXBaseSpecifier &BS = *RD->vbases_begin();
7182 assert(BS.isVirtual());
7183 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7184 return false;
7185 }
7186
7187 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007188 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007189 if (MI->isVirtual()) {
7190 SourceLocation MLoc = MI->getLocStart();
7191 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7192 return false;
7193 }
7194 }
7195
7196 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7197 }
7198
7199 // Looks like it's trivial!
7200 return true;
7201}
7202
Benjamin Kramer024e6192011-03-04 13:12:48 +00007203namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007204struct FindHiddenVirtualMethod {
7205 Sema *S;
7206 CXXMethodDecl *Method;
7207 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7208 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007209
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007210private:
7211 /// Check whether any most overriden method from MD in Methods
7212 static bool CheckMostOverridenMethods(
7213 const CXXMethodDecl *MD,
7214 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7215 if (MD->size_overridden_methods() == 0)
7216 return Methods.count(MD->getCanonicalDecl());
7217 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7218 E = MD->end_overridden_methods();
7219 I != E; ++I)
7220 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007221 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007222 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007223 }
7224
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007225public:
7226 /// Member lookup function that determines whether a given C++
7227 /// method overloads virtual methods in a base class without overriding any,
7228 /// to be used with CXXRecordDecl::lookupInBases().
7229 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7230 RecordDecl *BaseRecord =
7231 Specifier->getType()->getAs<RecordType>()->getDecl();
7232
7233 DeclarationName Name = Method->getDeclName();
7234 assert(Name.getNameKind() == DeclarationName::Identifier);
7235
7236 bool foundSameNameMethod = false;
7237 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7238 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7239 Path.Decls = Path.Decls.slice(1)) {
7240 NamedDecl *D = Path.Decls.front();
7241 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7242 MD = MD->getCanonicalDecl();
7243 foundSameNameMethod = true;
7244 // Interested only in hidden virtual methods.
7245 if (!MD->isVirtual())
7246 continue;
7247 // If the method we are checking overrides a method from its base
7248 // don't warn about the other overloaded methods. Clang deviates from
7249 // GCC by only diagnosing overloads of inherited virtual functions that
7250 // do not override any other virtual functions in the base. GCC's
7251 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7252 // function from a base class. These cases may be better served by a
7253 // warning (not specific to virtual functions) on call sites when the
7254 // call would select a different function from the base class, were it
7255 // visible.
7256 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7257 if (!S->IsOverload(Method, MD, false))
7258 return true;
7259 // Collect the overload only if its hidden.
7260 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7261 overloadedMethods.push_back(MD);
7262 }
7263 }
7264
7265 if (foundSameNameMethod)
7266 OverloadedMethods.append(overloadedMethods.begin(),
7267 overloadedMethods.end());
7268 return foundSameNameMethod;
7269 }
7270};
7271} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007272
David Blaikie282c92a2012-10-19 00:53:08 +00007273/// \brief Add the most overriden methods from MD to Methods
7274static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007275 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007276 if (MD->size_overridden_methods() == 0)
7277 Methods.insert(MD->getCanonicalDecl());
7278 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7279 E = MD->end_overridden_methods();
7280 I != E; ++I)
7281 AddMostOverridenMethods(*I, Methods);
7282}
7283
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007284/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007285/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007286void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7287 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007288 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007289 return;
7290
7291 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7292 /*bool RecordPaths=*/false,
7293 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007294 FindHiddenVirtualMethod FHVM;
7295 FHVM.Method = MD;
7296 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007297
7298 // Keep the base methods that were overriden or introduced in the subclass
7299 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007300 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007301 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7302 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7303 NamedDecl *ND = *I;
7304 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007305 ND = shad->getTargetDecl();
7306 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007307 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007308 }
7309
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007310 if (DC->lookupInBases(FHVM, Paths))
7311 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007312}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007313
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007314void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7315 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7316 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7317 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7318 PartialDiagnostic PD = PDiag(
7319 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7320 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7321 Diag(overloadedMD->getLocation(), PD);
7322 }
7323}
7324
7325/// \brief Diagnose methods which overload virtual methods in a base class
7326/// without overriding any.
7327void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7328 if (MD->isInvalidDecl())
7329 return;
7330
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007331 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007332 return;
7333
7334 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7335 FindHiddenVirtualMethods(MD, OverloadedMethods);
7336 if (!OverloadedMethods.empty()) {
7337 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7338 << MD << (OverloadedMethods.size() > 1);
7339
7340 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007341 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007342}
7343
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007344void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007345 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007346 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007347 SourceLocation RBrac,
7348 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007349 if (!TagDecl)
7350 return;
Mike Stump11289f42009-09-09 15:08:12 +00007351
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007352 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007353
Rafael Espindola06e1b132012-07-12 04:32:30 +00007354 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7355 if (l->getKind() != AttributeList::AT_Visibility)
7356 continue;
7357 l->setInvalid();
7358 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7359 l->getName();
7360 }
7361
David Blaikie751c5582011-09-22 02:58:26 +00007362 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007363 // strict aliasing violation!
7364 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007365 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007366
Douglas Gregor0be31a22010-07-02 17:43:08 +00007367 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007368 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007369}
7370
Douglas Gregor05379422008-11-03 17:51:48 +00007371/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7372/// special functions, such as the default constructor, copy
7373/// constructor, or destructor, to the given C++ class (C++
7374/// [special]p1). This routine can only be executed just before the
7375/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007376void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007377 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007378 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007379
Richard Smith5179eb72016-06-28 19:03:57 +00007380 if (ClassDecl->hasInheritedConstructor())
7381 DeclareImplicitDefaultConstructor(ClassDecl);
7382 }
Richard Smith12e79312016-05-13 06:47:56 +00007383
Richard Smitha87b7662016-05-13 18:48:05 +00007384 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007385 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007386
Richard Smith6b02d462012-12-08 08:32:28 +00007387 // If the properties or semantics of the copy constructor couldn't be
7388 // determined while the class was being declared, force a declaration
7389 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007390 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7391 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007392 DeclareImplicitCopyConstructor(ClassDecl);
7393 }
7394
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007395 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007396 ++ASTContext::NumImplicitMoveConstructors;
7397
Richard Smith12e79312016-05-13 06:47:56 +00007398 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7399 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007400 DeclareImplicitMoveConstructor(ClassDecl);
7401 }
7402
Richard Smitha87b7662016-05-13 18:48:05 +00007403 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007404 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007405
7406 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007407 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007408 // it shows up in the right place in the vtable and that we diagnose
7409 // problems with the implicit exception specification.
7410 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007411 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7412 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007413 DeclareImplicitCopyAssignment(ClassDecl);
7414 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007415
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007416 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007417 ++ASTContext::NumImplicitMoveAssignmentOperators;
7418
7419 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007420 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007421 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7422 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007423 DeclareImplicitMoveAssignment(ClassDecl);
7424 }
7425
Richard Smitha87b7662016-05-13 18:48:05 +00007426 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007427 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007428
7429 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007430 // have to declare the destructor immediately. This ensures that, e.g., it
7431 // shows up in the right place in the vtable and that we diagnose problems
7432 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007433 if (ClassDecl->isDynamicClass() ||
7434 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007435 DeclareImplicitDestructor(ClassDecl);
7436 }
Douglas Gregor05379422008-11-03 17:51:48 +00007437}
7438
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007439unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007440 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007441 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007442
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007443 // The order of template parameters is not important here. All names
7444 // get added to the same scope.
7445 SmallVector<TemplateParameterList *, 4> ParameterLists;
7446
7447 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7448 D = TD->getTemplatedDecl();
7449
7450 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7451 ParameterLists.push_back(PSD->getTemplateParameters());
7452
7453 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7454 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7455 ParameterLists.push_back(DD->getTemplateParameterList(i));
7456
7457 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7458 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7459 ParameterLists.push_back(FTD->getTemplateParameters());
7460 }
7461 }
7462
7463 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7464 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7465 ParameterLists.push_back(TD->getTemplateParameterList(i));
7466
7467 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7468 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7469 ParameterLists.push_back(CTD->getTemplateParameters());
7470 }
7471 }
7472
7473 unsigned Count = 0;
7474 for (TemplateParameterList *Params : ParameterLists) {
7475 if (Params->size() > 0)
7476 // Ignore explicit specializations; they don't contribute to the template
7477 // depth.
7478 ++Count;
7479 for (NamedDecl *Param : *Params) {
7480 if (Param->getDeclName()) {
7481 S->AddDecl(Param);
7482 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007483 }
7484 }
7485 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007486
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007487 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007488}
7489
John McCall48871652010-08-21 09:40:31 +00007490void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007491 if (!RecordD) return;
7492 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007493 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007494 PushDeclContext(S, Record);
7495}
7496
John McCall48871652010-08-21 09:40:31 +00007497void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007498 if (!RecordD) return;
7499 PopDeclContext();
7500}
7501
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007502/// This is used to implement the constant expression evaluation part of the
7503/// attribute enable_if extension. There is nothing in standard C++ which would
7504/// require reentering parameters.
7505void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7506 if (!Param)
7507 return;
7508
7509 S->AddDecl(Param);
7510 if (Param->getDeclName())
7511 IdResolver.AddDecl(Param);
7512}
7513
Douglas Gregor4d87df52008-12-16 21:30:33 +00007514/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7515/// parsing a top-level (non-nested) C++ class, and we are now
7516/// parsing those parts of the given Method declaration that could
7517/// not be parsed earlier (C++ [class.mem]p2), such as default
7518/// arguments. This action should enter the scope of the given
7519/// Method declaration as if we had just parsed the qualified method
7520/// name. However, it should not bring the parameters into scope;
7521/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007522void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007523}
7524
7525/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7526/// C++ method declaration. We're (re-)introducing the given
7527/// function parameter into scope for use in parsing later parts of
7528/// the method declaration. For example, we could see an
7529/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007530void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007531 if (!ParamD)
7532 return;
Mike Stump11289f42009-09-09 15:08:12 +00007533
John McCall48871652010-08-21 09:40:31 +00007534 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007535
7536 // If this parameter has an unparsed default argument, clear it out
7537 // to make way for the parsed default argument.
7538 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007539 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007540
John McCall48871652010-08-21 09:40:31 +00007541 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007542 if (Param->getDeclName())
7543 IdResolver.AddDecl(Param);
7544}
7545
7546/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7547/// processing the delayed method declaration for Method. The method
7548/// declaration is now considered finished. There may be a separate
7549/// ActOnStartOfFunctionDef action later (not necessarily
7550/// immediately!) for this method, if it was also defined inside the
7551/// class body.
John McCall48871652010-08-21 09:40:31 +00007552void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007553 if (!MethodD)
7554 return;
Mike Stump11289f42009-09-09 15:08:12 +00007555
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007556 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007557
John McCall48871652010-08-21 09:40:31 +00007558 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007559
7560 // Now that we have our default arguments, check the constructor
7561 // again. It could produce additional diagnostics or affect whether
7562 // the class has implicitly-declared destructors, among other
7563 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007564 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7565 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007566
7567 // Check the default arguments, which we may have added.
7568 if (!Method->isInvalidDecl())
7569 CheckCXXDefaultArguments(Method);
7570}
7571
Douglas Gregor831c93f2008-11-05 20:51:48 +00007572/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007573/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007574/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007575/// emit diagnostics and set the invalid bit to true. In any case, the type
7576/// will be updated to reflect a well-formed type for the constructor and
7577/// returned.
7578QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007579 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007580 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007581
7582 // C++ [class.ctor]p3:
7583 // A constructor shall not be virtual (10.3) or static (9.4). A
7584 // constructor can be invoked for a const, volatile or const
7585 // volatile object. A constructor shall not be declared const,
7586 // volatile, or const volatile (9.3.2).
7587 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007588 if (!D.isInvalidType())
7589 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7590 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7591 << SourceRange(D.getIdentifierLoc());
7592 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007593 }
John McCall8e7d6562010-08-26 03:08:43 +00007594 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007595 if (!D.isInvalidType())
7596 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7597 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7598 << SourceRange(D.getIdentifierLoc());
7599 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007600 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007601 }
Mike Stump11289f42009-09-09 15:08:12 +00007602
David Majnemer03f705f2014-07-08 18:18:04 +00007603 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7604 diagnoseIgnoredQualifiers(
7605 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7606 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7607 D.getDeclSpec().getRestrictSpecLoc(),
7608 D.getDeclSpec().getAtomicSpecLoc());
7609 D.setInvalidType();
7610 }
7611
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007612 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007613 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007614 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7616 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007617 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007618 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7619 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007620 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007621 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7622 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007623 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007624 }
Mike Stump11289f42009-09-09 15:08:12 +00007625
Douglas Gregordb9d6642011-01-26 05:01:58 +00007626 // C++0x [class.ctor]p4:
7627 // A constructor shall not be declared with a ref-qualifier.
7628 if (FTI.hasRefQualifier()) {
7629 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7630 << FTI.RefQualifierIsLValueRef
7631 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7632 D.setInvalidType();
7633 }
7634
Douglas Gregor831c93f2008-11-05 20:51:48 +00007635 // Rebuild the function type "R" without any type qualifiers (in
7636 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007637 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007638 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007639 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007640 return R;
7641
7642 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7643 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007644 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007645
7646 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007647}
7648
Douglas Gregor4d87df52008-12-16 21:30:33 +00007649/// CheckConstructor - Checks a fully-formed constructor for
7650/// well-formedness, issuing any diagnostics required. Returns true if
7651/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007652void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007653 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007654 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7655 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007656 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007657
7658 // C++ [class.copy]p3:
7659 // A declaration of a constructor for a class X is ill-formed if
7660 // its first parameter is of type (optionally cv-qualified) X and
7661 // either there are no other parameters or else all other
7662 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007663 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007664 ((Constructor->getNumParams() == 1) ||
7665 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007666 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7667 Constructor->getTemplateSpecializationKind()
7668 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007669 QualType ParamType = Constructor->getParamDecl(0)->getType();
7670 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7671 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007672 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007673 const char *ConstRef
7674 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7675 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007676 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007677 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007678
7679 // FIXME: Rather that making the constructor invalid, we should endeavor
7680 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007681 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007682 }
7683 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007684}
7685
John McCalldeb646e2010-08-04 01:04:25 +00007686/// CheckDestructor - Checks a fully-formed destructor definition for
7687/// well-formedness, issuing any diagnostics required. Returns true
7688/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007689bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007690 CXXRecordDecl *RD = Destructor->getParent();
7691
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007692 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007693 SourceLocation Loc;
7694
7695 if (!Destructor->isImplicit())
7696 Loc = Destructor->getLocation();
7697 else
7698 Loc = RD->getLocation();
7699
7700 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007701 if (FunctionDecl *OperatorDelete =
7702 FindDeallocationFunctionForDestructor(Loc, RD)) {
7703 MarkFunctionReferenced(Loc, OperatorDelete);
7704 Destructor->setOperatorDelete(OperatorDelete);
7705 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007706 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007707
7708 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007709}
7710
Douglas Gregor831c93f2008-11-05 20:51:48 +00007711/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7712/// the well-formednes of the destructor declarator @p D with type @p
7713/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007714/// emit diagnostics and set the declarator to invalid. Even if this happens,
7715/// will be updated to reflect a well-formed type for the destructor and
7716/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007717QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007718 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007719 // C++ [class.dtor]p1:
7720 // [...] A typedef-name that names a class is a class-name
7721 // (7.1.3); however, a typedef-name that names a class shall not
7722 // be used as the identifier in the declarator for a destructor
7723 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007724 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007725 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007726 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007727 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007728 else if (const TemplateSpecializationType *TST =
7729 DeclaratorType->getAs<TemplateSpecializationType>())
7730 if (TST->isTypeAlias())
7731 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7732 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007733
7734 // C++ [class.dtor]p2:
7735 // A destructor is used to destroy objects of its class type. A
7736 // destructor takes no parameters, and no return type can be
7737 // specified for it (not even void). The address of a destructor
7738 // shall not be taken. A destructor shall not be static. A
7739 // destructor can be invoked for a const, volatile or const
7740 // volatile object. A destructor shall not be declared const,
7741 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007742 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007743 if (!D.isInvalidType())
7744 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7745 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007746 << SourceRange(D.getIdentifierLoc())
7747 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7748
John McCall8e7d6562010-08-26 03:08:43 +00007749 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007750 }
David Majnemer03f705f2014-07-08 18:18:04 +00007751 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007752 // Destructors don't have return types, but the parser will
7753 // happily parse something like:
7754 //
7755 // class X {
7756 // float ~X();
7757 // };
7758 //
7759 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007760 if (D.getDeclSpec().hasTypeSpecifier())
7761 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7762 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7763 << SourceRange(D.getIdentifierLoc());
7764 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7765 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7766 SourceLocation(),
7767 D.getDeclSpec().getConstSpecLoc(),
7768 D.getDeclSpec().getVolatileSpecLoc(),
7769 D.getDeclSpec().getRestrictSpecLoc(),
7770 D.getDeclSpec().getAtomicSpecLoc());
7771 D.setInvalidType();
7772 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007773 }
Mike Stump11289f42009-09-09 15:08:12 +00007774
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007775 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007776 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007777 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007778 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7779 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007780 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007781 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7782 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007783 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007784 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7785 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007786 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007787 }
7788
Douglas Gregordb9d6642011-01-26 05:01:58 +00007789 // C++0x [class.dtor]p2:
7790 // A destructor shall not be declared with a ref-qualifier.
7791 if (FTI.hasRefQualifier()) {
7792 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7793 << FTI.RefQualifierIsLValueRef
7794 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7795 D.setInvalidType();
7796 }
7797
Douglas Gregor831c93f2008-11-05 20:51:48 +00007798 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007799 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007800 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7801
7802 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007803 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007804 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007805 }
7806
Mike Stump11289f42009-09-09 15:08:12 +00007807 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007808 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007809 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007810 D.setInvalidType();
7811 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007812
7813 // Rebuild the function type "R" without any type qualifiers or
7814 // parameters (in case any of the errors above fired) and with
7815 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007816 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007817 if (!D.isInvalidType())
7818 return R;
7819
Douglas Gregor95755162010-07-01 05:10:53 +00007820 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007821 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7822 EPI.Variadic = false;
7823 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007824 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007825 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007826}
7827
Craig Toppere335f252015-10-04 04:53:55 +00007828static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007829 if (Before.isInvalid())
7830 return;
7831 R.setBegin(Before.getBegin());
7832 if (R.getEnd().isInvalid())
7833 R.setEnd(Before.getEnd());
7834}
7835
Craig Toppere335f252015-10-04 04:53:55 +00007836static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007837 if (After.isInvalid())
7838 return;
7839 if (R.getBegin().isInvalid())
7840 R.setBegin(After.getBegin());
7841 R.setEnd(After.getEnd());
7842}
7843
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007844/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7845/// well-formednes of the conversion function declarator @p D with
7846/// type @p R. If there are any errors in the declarator, this routine
7847/// will emit diagnostics and return true. Otherwise, it will return
7848/// false. Either way, the type @p R will be updated to reflect a
7849/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007850void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007851 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007852 // C++ [class.conv.fct]p1:
7853 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007854 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007855 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007856 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007857 if (!D.isInvalidType())
7858 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007859 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7860 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007861 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007862 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007863 }
John McCall212fa2e2010-04-13 00:04:31 +00007864
Richard Smitha865a162014-12-19 02:07:47 +00007865 TypeSourceInfo *ConvTSI = nullptr;
7866 QualType ConvType =
7867 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007868
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007869 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007870 // Conversion functions don't have return types, but the parser will
7871 // happily parse something like:
7872 //
7873 // class X {
7874 // float operator bool();
7875 // };
7876 //
7877 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00007878 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7879 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7880 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00007881 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007882 }
7883
John McCall212fa2e2010-04-13 00:04:31 +00007884 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7885
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007886 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00007887 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007888 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7889
7890 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007891 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007892 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00007893 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007894 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007895 D.setInvalidType();
7896 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007897
John McCall212fa2e2010-04-13 00:04:31 +00007898 // Diagnose "&operator bool()" and other such nonsense. This
7899 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007900 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007901 bool NeedsTypedef = false;
7902 SourceRange Before, After;
7903
7904 // Walk the chunks and extract information on them for our diagnostic.
7905 bool PastFunctionChunk = false;
7906 for (auto &Chunk : D.type_objects()) {
7907 switch (Chunk.Kind) {
7908 case DeclaratorChunk::Function:
7909 if (!PastFunctionChunk) {
7910 if (Chunk.Fun.HasTrailingReturnType) {
7911 TypeSourceInfo *TRT = nullptr;
7912 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7913 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7914 }
7915 PastFunctionChunk = true;
7916 break;
7917 }
7918 // Fall through.
7919 case DeclaratorChunk::Array:
7920 NeedsTypedef = true;
7921 extendRight(After, Chunk.getSourceRange());
7922 break;
7923
7924 case DeclaratorChunk::Pointer:
7925 case DeclaratorChunk::BlockPointer:
7926 case DeclaratorChunk::Reference:
7927 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007928 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007929 extendLeft(Before, Chunk.getSourceRange());
7930 break;
7931
7932 case DeclaratorChunk::Paren:
7933 extendLeft(Before, Chunk.Loc);
7934 extendRight(After, Chunk.EndLoc);
7935 break;
7936 }
7937 }
7938
7939 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7940 After.isValid() ? After.getBegin() :
7941 D.getIdentifierLoc();
7942 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7943 DB << Before << After;
7944
7945 if (!NeedsTypedef) {
7946 DB << /*don't need a typedef*/0;
7947
7948 // If we can provide a correct fix-it hint, do so.
7949 if (After.isInvalid() && ConvTSI) {
7950 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007951 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007952 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7953 << FixItHint::CreateInsertionFromRange(
7954 InsertLoc, CharSourceRange::getTokenRange(Before))
7955 << FixItHint::CreateRemoval(Before);
7956 }
7957 } else if (!Proto->getReturnType()->isDependentType()) {
7958 DB << /*typedef*/1 << Proto->getReturnType();
7959 } else if (getLangOpts().CPlusPlus11) {
7960 DB << /*alias template*/2 << Proto->getReturnType();
7961 } else {
7962 DB << /*might not be fixable*/3;
7963 }
7964
7965 // Recover by incorporating the other type chunks into the result type.
7966 // Note, this does *not* change the name of the function. This is compatible
7967 // with the GCC extension:
7968 // struct S { &operator int(); } s;
7969 // int &r = s.operator int(); // ok in GCC
7970 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007971 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007972 }
7973
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007974 // C++ [class.conv.fct]p4:
7975 // The conversion-type-id shall not represent a function type nor
7976 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007977 if (ConvType->isArrayType()) {
7978 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7979 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007980 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007981 } else if (ConvType->isFunctionType()) {
7982 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7983 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007984 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007985 }
7986
7987 // Rebuild the function type "R" without any parameters (in case any
7988 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007989 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007990 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007991 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007992
Douglas Gregor5fb53972009-01-14 15:45:31 +00007993 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007994 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007995 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007996 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007997 diag::warn_cxx98_compat_explicit_conversion_functions :
7998 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007999 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008000}
8001
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008002/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8003/// the declaration of the given C++ conversion function. This routine
8004/// is responsible for recording the conversion function in the C++
8005/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008006Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008007 assert(Conversion && "Expected to receive a conversion function declaration");
8008
Douglas Gregor4287b372008-12-12 08:25:50 +00008009 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008010
8011 // Make sure we aren't redeclaring the conversion function.
8012 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008013
8014 // C++ [class.conv.fct]p1:
8015 // [...] A conversion function is never used to convert a
8016 // (possibly cv-qualified) object to the (possibly cv-qualified)
8017 // same object type (or a reference to it), to a (possibly
8018 // cv-qualified) base class of that type (or a reference to it),
8019 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008020 // FIXME: Suppress this warning if the conversion function ends up being a
8021 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008022 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008023 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008024 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008025 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008026 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8027 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008028 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008029 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008030 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8031 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008032 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008033 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008034 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008035 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008036 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008037 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008038 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008039 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008040 }
8041
Douglas Gregor457104e2010-09-29 04:25:11 +00008042 if (FunctionTemplateDecl *ConversionTemplate
8043 = Conversion->getDescribedFunctionTemplate())
8044 return ConversionTemplate;
8045
John McCall48871652010-08-21 09:40:31 +00008046 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008047}
8048
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008049//===----------------------------------------------------------------------===//
8050// Namespace Handling
8051//===----------------------------------------------------------------------===//
8052
Richard Smith45bb8852012-10-04 22:13:39 +00008053/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8054/// reopened.
8055static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8056 SourceLocation Loc,
8057 IdentifierInfo *II, bool *IsInline,
8058 NamespaceDecl *PrevNS) {
8059 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008060
Richard Smithf501cc32012-10-05 01:46:25 +00008061 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8062 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8063 // inline namespaces, with the intention of bringing names into namespace std.
8064 //
8065 // We support this just well enough to get that case working; this is not
8066 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008067 if (*IsInline && II && II->getName().startswith("__atomic") &&
8068 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008069 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008070 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8071 NS = NS->getPreviousDecl())
8072 NS->setInline(*IsInline);
8073 // Patch up the lookup table for the containing namespace. This isn't really
8074 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008075 for (auto *I : PrevNS->decls())
8076 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008077 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8078 return;
8079 }
8080
8081 if (PrevNS->isInline())
8082 // The user probably just forgot the 'inline', so suggest that it
8083 // be added back.
8084 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8085 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8086 else
Richard Smith360cb252016-09-30 23:16:08 +00008087 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008088
8089 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8090 *IsInline = PrevNS->isInline();
8091}
John McCallb1be5232010-08-26 09:15:37 +00008092
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008093/// ActOnStartNamespaceDef - This is called at the start of a namespace
8094/// definition.
John McCall48871652010-08-21 09:40:31 +00008095Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008096 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008097 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008098 SourceLocation IdentLoc,
8099 IdentifierInfo *II,
8100 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008101 AttributeList *AttrList,
8102 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008103 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8104 // For anonymous namespace, take the location of the left brace.
8105 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008106 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008107 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008108 bool IsStd = false;
8109 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008110 Scope *DeclRegionScope = NamespcScope->getParent();
8111
Craig Topperc3ec1492014-05-26 06:22:03 +00008112 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008113 if (II) {
8114 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008115 // The identifier in an original-namespace-definition shall not
8116 // have been previously defined in the declarative region in
8117 // which the original-namespace-definition appears. The
8118 // identifier in an original-namespace-definition is the name of
8119 // the namespace. Subsequently in that declarative region, it is
8120 // treated as an original-namespace-name.
8121 //
8122 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008123 // look through using directives, just look for any ordinary names
8124 // as if by qualified name lookup.
8125 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8126 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008127 NamedDecl *PrevDecl =
8128 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008129 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008130
Douglas Gregore57e7522012-01-07 09:11:48 +00008131 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008132 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008133 if (IsInline != PrevNS->isInline())
8134 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8135 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008136 } else if (PrevDecl) {
8137 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008138 Diag(Loc, diag::err_redefinition_different_kind)
8139 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008140 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008141 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008142 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008143 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008144 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008145 // This is the first "real" definition of the namespace "std", so update
8146 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008147 PrevNS = getStdNamespace();
8148 IsStd = true;
8149 AddToKnown = !IsInline;
8150 } else {
8151 // We've seen this namespace for the first time.
8152 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008153 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008154 } else {
John McCall4fa53422009-10-01 00:25:31 +00008155 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008156
8157 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008158 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008159 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008160 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008161 } else {
8162 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008163 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008164 }
8165
Richard Smith45bb8852012-10-04 22:13:39 +00008166 if (PrevNS && IsInline != PrevNS->isInline())
8167 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8168 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008169 }
8170
8171 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8172 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008173 if (IsInvalid)
8174 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008175
8176 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008177
Douglas Gregore57e7522012-01-07 09:11:48 +00008178 // FIXME: Should we be merging attributes?
8179 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008180 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008181
8182 if (IsStd)
8183 StdNamespace = Namespc;
8184 if (AddToKnown)
8185 KnownNamespaces[Namespc] = false;
8186
8187 if (II) {
8188 PushOnScopeChains(Namespc, DeclRegionScope);
8189 } else {
8190 // Link the anonymous namespace into its parent.
8191 DeclContext *Parent = CurContext->getRedeclContext();
8192 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8193 TU->setAnonymousNamespace(Namespc);
8194 } else {
8195 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008196 }
John McCall4fa53422009-10-01 00:25:31 +00008197
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008198 CurContext->addDecl(Namespc);
8199
John McCall4fa53422009-10-01 00:25:31 +00008200 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8201 // behaves as if it were replaced by
8202 // namespace unique { /* empty body */ }
8203 // using namespace unique;
8204 // namespace unique { namespace-body }
8205 // where all occurrences of 'unique' in a translation unit are
8206 // replaced by the same identifier and this identifier differs
8207 // from all other identifiers in the entire program.
8208
8209 // We just create the namespace with an empty name and then add an
8210 // implicit using declaration, just like the standard suggests.
8211 //
8212 // CodeGen enforces the "universally unique" aspect by giving all
8213 // declarations semantically contained within an anonymous
8214 // namespace internal linkage.
8215
Douglas Gregore57e7522012-01-07 09:11:48 +00008216 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008217 UD = UsingDirectiveDecl::Create(Context, Parent,
8218 /* 'using' */ LBrace,
8219 /* 'namespace' */ SourceLocation(),
8220 /* qualifier */ NestedNameSpecifierLoc(),
8221 /* identifier */ SourceLocation(),
8222 Namespc,
8223 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008224 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008225 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008226 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008227 }
8228
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008229 ActOnDocumentableDecl(Namespc);
8230
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008231 // Although we could have an invalid decl (i.e. the namespace name is a
8232 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008233 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8234 // for the namespace has the declarations that showed up in that particular
8235 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008236 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008237 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008238}
8239
Sebastian Redla6602e92009-11-23 15:34:23 +00008240/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8241/// is a namespace alias, returns the namespace it points to.
8242static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8243 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8244 return AD->getNamespace();
8245 return dyn_cast_or_null<NamespaceDecl>(D);
8246}
8247
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008248/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8249/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008250void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008251 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8252 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008253 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008254 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008255 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008256 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008257}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008258
John McCall28a0cf72010-08-25 07:42:41 +00008259CXXRecordDecl *Sema::getStdBadAlloc() const {
8260 return cast_or_null<CXXRecordDecl>(
8261 StdBadAlloc.get(Context.getExternalSource()));
8262}
8263
Richard Smith96269c52016-09-29 22:49:46 +00008264EnumDecl *Sema::getStdAlignValT() const {
8265 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8266}
8267
John McCall28a0cf72010-08-25 07:42:41 +00008268NamespaceDecl *Sema::getStdNamespace() const {
8269 return cast_or_null<NamespaceDecl>(
8270 StdNamespace.get(Context.getExternalSource()));
8271}
8272
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008273NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8274 if (!StdExperimentalNamespaceCache) {
8275 if (auto Std = getStdNamespace()) {
8276 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8277 SourceLocation(), LookupNamespaceName);
8278 if (!LookupQualifiedName(Result, Std) ||
8279 !(StdExperimentalNamespaceCache =
8280 Result.getAsSingle<NamespaceDecl>()))
8281 Result.suppressDiagnostics();
8282 }
8283 }
8284 return StdExperimentalNamespaceCache;
8285}
8286
Douglas Gregorcdf87022010-06-29 17:53:46 +00008287/// \brief Retrieve the special "std" namespace, which may require us to
8288/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008289NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008290 if (!StdNamespace) {
8291 // The "std" namespace has not yet been defined, so build one implicitly.
8292 StdNamespace = NamespaceDecl::Create(Context,
8293 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008294 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008295 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008296 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008297 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008298 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008299 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008300
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008301 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008302}
8303
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008304bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008305 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008306 "Looking for std::initializer_list outside of C++.");
8307
8308 // We're looking for implicit instantiations of
8309 // template <typename E> class std::initializer_list.
8310
8311 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8312 return false;
8313
Craig Topperc3ec1492014-05-26 06:22:03 +00008314 ClassTemplateDecl *Template = nullptr;
8315 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008316
Sebastian Redl43144e72012-01-17 22:49:58 +00008317 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008318
Sebastian Redl43144e72012-01-17 22:49:58 +00008319 ClassTemplateSpecializationDecl *Specialization =
8320 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8321 if (!Specialization)
8322 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008323
Sebastian Redl43144e72012-01-17 22:49:58 +00008324 Template = Specialization->getSpecializedTemplate();
8325 Arguments = Specialization->getTemplateArgs().data();
8326 } else if (const TemplateSpecializationType *TST =
8327 Ty->getAs<TemplateSpecializationType>()) {
8328 Template = dyn_cast_or_null<ClassTemplateDecl>(
8329 TST->getTemplateName().getAsTemplateDecl());
8330 Arguments = TST->getArgs();
8331 }
8332 if (!Template)
8333 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008334
8335 if (!StdInitializerList) {
8336 // Haven't recognized std::initializer_list yet, maybe this is it.
8337 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8338 if (TemplateClass->getIdentifier() !=
8339 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008340 !getStdNamespace()->InEnclosingNamespaceSetOf(
8341 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008342 return false;
8343 // This is a template called std::initializer_list, but is it the right
8344 // template?
8345 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008346 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008347 return false;
8348 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8349 return false;
8350
8351 // It's the right template.
8352 StdInitializerList = Template;
8353 }
8354
Richard Smith7d7dee72015-02-24 03:30:14 +00008355 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008356 return false;
8357
8358 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008359 if (Element)
8360 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008361 return true;
8362}
8363
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008364static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8365 NamespaceDecl *Std = S.getStdNamespace();
8366 if (!Std) {
8367 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008368 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008369 }
8370
8371 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8372 Loc, Sema::LookupOrdinaryName);
8373 if (!S.LookupQualifiedName(Result, Std)) {
8374 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008375 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008376 }
8377 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8378 if (!Template) {
8379 Result.suppressDiagnostics();
8380 // We found something weird. Complain about the first thing we found.
8381 NamedDecl *Found = *Result.begin();
8382 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008384 }
8385
8386 // We found some template called std::initializer_list. Now verify that it's
8387 // correct.
8388 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008389 if (Params->getMinRequiredArguments() != 1 ||
8390 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008391 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008392 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008393 }
8394
8395 return Template;
8396}
8397
8398QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8399 if (!StdInitializerList) {
8400 StdInitializerList = LookupStdInitializerList(*this, Loc);
8401 if (!StdInitializerList)
8402 return QualType();
8403 }
8404
8405 TemplateArgumentListInfo Args(Loc, Loc);
8406 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8407 Context.getTrivialTypeSourceInfo(Element,
8408 Loc)));
8409 return Context.getCanonicalType(
8410 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8411}
8412
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008413bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8414 // C++ [dcl.init.list]p2:
8415 // A constructor is an initializer-list constructor if its first parameter
8416 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8417 // std::initializer_list<E> for some type E, and either there are no other
8418 // parameters or else all other parameters have default arguments.
8419 if (Ctor->getNumParams() < 1 ||
8420 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8421 return false;
8422
8423 QualType ArgType = Ctor->getParamDecl(0)->getType();
8424 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8425 ArgType = RT->getPointeeType().getUnqualifiedType();
8426
Craig Topperc3ec1492014-05-26 06:22:03 +00008427 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008428}
8429
Douglas Gregora172e082011-03-26 22:25:30 +00008430/// \brief Determine whether a using statement is in a context where it will be
8431/// apply in all contexts.
8432static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8433 switch (CurContext->getDeclKind()) {
8434 case Decl::TranslationUnit:
8435 return true;
8436 case Decl::LinkageSpec:
8437 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8438 default:
8439 return false;
8440 }
8441}
8442
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008443namespace {
8444
8445// Callback to only accept typo corrections that are namespaces.
8446class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008447public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008448 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008449 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008450 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008451 return false;
8452 }
8453};
8454
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008455}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008456
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008457static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8458 CXXScopeSpec &SS,
8459 SourceLocation IdentLoc,
8460 IdentifierInfo *Ident) {
8461 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008462 if (TypoCorrection Corrected =
8463 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8464 llvm::make_unique<NamespaceValidatorCCC>(),
8465 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008466 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008467 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8468 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008469 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008470 S.diagnoseTypo(Corrected,
8471 S.PDiag(diag::err_using_directive_member_suggest)
8472 << Ident << DC << DroppedSpecifier << SS.getRange(),
8473 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008474 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008475 S.diagnoseTypo(Corrected,
8476 S.PDiag(diag::err_using_directive_suggest) << Ident,
8477 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008478 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008479 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008480 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008481 }
8482 return false;
8483}
8484
John McCall48871652010-08-21 09:40:31 +00008485Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008486 SourceLocation UsingLoc,
8487 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008488 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008489 SourceLocation IdentLoc,
8490 IdentifierInfo *NamespcName,
8491 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008492 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8493 assert(NamespcName && "Invalid NamespcName.");
8494 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008495
8496 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008497 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008498 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008499 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008500
Craig Topperc3ec1492014-05-26 06:22:03 +00008501 UsingDirectiveDecl *UDir = nullptr;
8502 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008503 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008504 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008505
Douglas Gregor34074322009-01-14 22:20:51 +00008506 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008507 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8508 LookupParsedName(R, S, &SS);
8509 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008510 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008511
Douglas Gregorcdf87022010-06-29 17:53:46 +00008512 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008513 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008514 // Allow "using namespace std;" or "using namespace ::std;" even if
8515 // "std" hasn't been defined yet, for GCC compatibility.
8516 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8517 NamespcName->isStr("std")) {
8518 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008519 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008520 R.resolveKind();
8521 }
8522 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008523 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008524 }
8525
John McCall9f3059a2009-10-09 21:13:30 +00008526 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008527 NamedDecl *Named = R.getRepresentativeDecl();
8528 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8529 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008530
Nico Riecke50e59a2014-11-24 17:29:52 +00008531 // The use of a nested name specifier may trigger deprecation warnings.
8532 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008533
Douglas Gregor889ceb72009-02-03 19:21:40 +00008534 // C++ [namespace.udir]p1:
8535 // A using-directive specifies that the names in the nominated
8536 // namespace can be used in the scope in which the
8537 // using-directive appears after the using-directive. During
8538 // unqualified name lookup (3.4.1), the names appear as if they
8539 // were declared in the nearest enclosing namespace which
8540 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008541 // namespace. [Note: in this context, "contains" means "contains
8542 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008543
8544 // Find enclosing context containing both using-directive and
8545 // nominated namespace.
8546 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8547 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8548 CommonAncestor = CommonAncestor->getParent();
8549
Sebastian Redla6602e92009-11-23 15:34:23 +00008550 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008551 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008552 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008553
Douglas Gregora172e082011-03-26 22:25:30 +00008554 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008555 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008556 Diag(IdentLoc, diag::warn_using_directive_in_header);
8557 }
8558
Douglas Gregor889ceb72009-02-03 19:21:40 +00008559 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008560 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008561 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008562 }
8563
Richard Smith54ecd982013-02-20 19:22:51 +00008564 if (UDir)
8565 ProcessDeclAttributeList(S, UDir, AttrList);
8566
John McCall48871652010-08-21 09:40:31 +00008567 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008568}
8569
8570void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008571 // If the scope has an associated entity and the using directive is at
8572 // namespace or translation unit scope, add the UsingDirectiveDecl into
8573 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008574 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008575 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008576 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008577 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008578 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008579 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008580 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008581}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008582
Douglas Gregorfec52632009-06-20 00:51:54 +00008583
John McCall48871652010-08-21 09:40:31 +00008584Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008585 AccessSpecifier AS,
8586 bool HasUsingKeyword,
8587 SourceLocation UsingLoc,
8588 CXXScopeSpec &SS,
8589 UnqualifiedId &Name,
8590 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008591 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00008592 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008593 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008594
Douglas Gregor220f4272009-11-04 16:30:06 +00008595 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008596 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008597 case UnqualifiedId::IK_Identifier:
8598 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008599 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008600 case UnqualifiedId::IK_ConversionFunctionId:
8601 break;
8602
8603 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008604 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008605 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008606 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008607 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008608 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008609 diag::err_using_decl_constructor)
8610 << SS.getRange();
8611
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008612 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008613
Craig Topperc3ec1492014-05-26 06:22:03 +00008614 return nullptr;
8615
Douglas Gregor220f4272009-11-04 16:30:06 +00008616 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008617 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008618 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008619 return nullptr;
8620
Douglas Gregor220f4272009-11-04 16:30:06 +00008621 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008622 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008623 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008624 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00008625 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008626
8627 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8628 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008629 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008630 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008631
Richard Smithc2bc61b2013-03-18 21:12:30 +00008632 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00008633 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008634 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008635 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8636 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008637 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008638 }
8639
Douglas Gregorc4356532010-12-16 00:46:58 +00008640 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8641 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00008642 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00008643
John McCall3f746822009-11-17 05:59:44 +00008644 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008645 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008646 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008647 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00008648 if (UD)
8649 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008650
John McCall48871652010-08-21 09:40:31 +00008651 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008652}
8653
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008654/// \brief Determine whether a using declaration considers the given
8655/// declarations as "equivalent", e.g., if they are redeclarations of
8656/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008657static bool
8658IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8659 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008660 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008661
Richard Smithdda56e42011-04-15 14:24:37 +00008662 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008663 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008664 return Context.hasSameType(TD1->getUnderlyingType(),
8665 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008666
8667 return false;
8668}
8669
8670
John McCall84d87672009-12-10 09:41:52 +00008671/// Determines whether to create a using shadow decl for a particular
8672/// decl, given the set of decls existing prior to this using lookup.
8673bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008674 const LookupResult &Previous,
8675 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008676 // Diagnose finding a decl which is not from a base class of the
8677 // current class. We do this now because there are cases where this
8678 // function will silently decide not to build a shadow decl, which
8679 // will pre-empt further diagnostics.
8680 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008681 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008682 // the qualifier.
8683 //
8684 // FIXME: diagnose the following if we care enough:
8685 // struct A { int foo; };
8686 // struct B : A { using A::foo; };
8687 // template <class T> struct C : A {};
8688 // template <class T> struct D : C<T> { using B::foo; } // <---
8689 // This is invalid (during instantiation) in C++03 because B::foo
8690 // resolves to the using decl in B, which is not a base class of D<T>.
8691 // We can't diagnose it immediately because C<T> is an unknown
8692 // specialization. The UsingShadowDecl in D<T> then points directly
8693 // to A::foo, which will look well-formed when we instantiate.
8694 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008695 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008696 DeclContext *OrigDC = Orig->getDeclContext();
8697
8698 // Handle enums and anonymous structs.
8699 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8700 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8701 while (OrigRec->isAnonymousStructOrUnion())
8702 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8703
8704 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8705 if (OrigDC == CurContext) {
8706 Diag(Using->getLocation(),
8707 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008708 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008709 Diag(Orig->getLocation(), diag::note_using_decl_target);
8710 return true;
8711 }
8712
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008713 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00008714 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008715 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00008716 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008717 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008718 Diag(Orig->getLocation(), diag::note_using_decl_target);
8719 return true;
8720 }
8721 }
8722
8723 if (Previous.empty()) return false;
8724
8725 NamedDecl *Target = Orig;
8726 if (isa<UsingShadowDecl>(Target))
8727 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8728
John McCalla17e83e2009-12-11 02:33:26 +00008729 // If the target happens to be one of the previous declarations, we
8730 // don't have a conflict.
8731 //
8732 // FIXME: but we might be increasing its access, in which case we
8733 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008734 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008735 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00008736 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8737 I != E; ++I) {
8738 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00008739 // We can have UsingDecls in our Previous results because we use the same
8740 // LookupResult for checking whether the UsingDecl itself is a valid
8741 // redeclaration.
8742 if (isa<UsingDecl>(D))
8743 continue;
8744
Richard Smithfd8634a2013-10-23 02:17:46 +00008745 if (IsEquivalentForUsingDecl(Context, D, Target)) {
8746 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8747 PrevShadow = Shadow;
8748 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00008749 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8750 // We don't conflict with an existing using shadow decl of an equivalent
8751 // declaration, but we're not a redeclaration of it.
8752 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00008753 }
John McCalla17e83e2009-12-11 02:33:26 +00008754
Richard Smithf091e122015-09-15 01:28:55 +00008755 if (isVisible(D))
8756 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00008757 }
8758
Richard Smithfd8634a2013-10-23 02:17:46 +00008759 if (FoundEquivalentDecl)
8760 return false;
8761
Alp Tokera2794f92014-01-22 07:29:52 +00008762 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008763 NamedDecl *OldDecl = nullptr;
8764 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8765 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00008766 case Ovl_Overload:
8767 return false;
8768
8769 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00008770 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008771 break;
Richard Smith18819302014-02-06 01:31:33 +00008772
John McCall84d87672009-12-10 09:41:52 +00008773 // We found a decl with the exact signature.
8774 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00008775 // If we're in a record, we want to hide the target, so we
8776 // return true (without a diagnostic) to tell the caller not to
8777 // build a shadow decl.
8778 if (CurContext->isRecord())
8779 return true;
8780
8781 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00008782 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008783 break;
8784 }
8785
8786 Diag(Target->getLocation(), diag::note_using_decl_target);
8787 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8788 return true;
8789 }
8790
8791 // Target is not a function.
8792
John McCall84d87672009-12-10 09:41:52 +00008793 if (isa<TagDecl>(Target)) {
8794 // No conflict between a tag and a non-tag.
8795 if (!Tag) return false;
8796
John McCalle29c5cd2009-12-10 19:51:03 +00008797 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008798 Diag(Target->getLocation(), diag::note_using_decl_target);
8799 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8800 return true;
8801 }
8802
8803 // No conflict between a tag and a non-tag.
8804 if (!NonTag) return false;
8805
John McCalle29c5cd2009-12-10 19:51:03 +00008806 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008807 Diag(Target->getLocation(), diag::note_using_decl_target);
8808 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8809 return true;
8810}
8811
Richard Smith5179eb72016-06-28 19:03:57 +00008812/// Determine whether a direct base class is a virtual base class.
8813static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8814 if (!Derived->getNumVBases())
8815 return false;
8816 for (auto &B : Derived->bases())
8817 if (B.getType()->getAsCXXRecordDecl() == Base)
8818 return B.isVirtual();
8819 llvm_unreachable("not a direct base class");
8820}
8821
John McCall3f746822009-11-17 05:59:44 +00008822/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00008823UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00008824 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00008825 NamedDecl *Orig,
8826 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00008827 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00008828 NamedDecl *Target = Orig;
8829 if (isa<UsingShadowDecl>(Target)) {
8830 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8831 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00008832 }
Richard Smithfd8634a2013-10-23 02:17:46 +00008833
Richard Smith5179eb72016-06-28 19:03:57 +00008834 NamedDecl *NonTemplateTarget = Target;
8835 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8836 NonTemplateTarget = TargetTD->getTemplatedDecl();
8837
8838 UsingShadowDecl *Shadow;
8839 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8840 bool IsVirtualBase =
8841 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8842 UD->getQualifier()->getAsRecordDecl());
8843 Shadow = ConstructorUsingShadowDecl::Create(
8844 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8845 } else {
8846 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8847 Target);
8848 }
John McCall3f746822009-11-17 05:59:44 +00008849 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00008850
Douglas Gregor457104e2010-09-29 04:25:11 +00008851 Shadow->setAccess(UD->getAccess());
8852 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8853 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00008854
8855 Shadow->setPreviousDecl(PrevDecl);
8856
John McCall3f746822009-11-17 05:59:44 +00008857 if (S)
John McCall3969e302009-12-08 07:46:18 +00008858 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00008859 else
John McCall3969e302009-12-08 07:46:18 +00008860 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00008861
John McCall3969e302009-12-08 07:46:18 +00008862
John McCall84d87672009-12-10 09:41:52 +00008863 return Shadow;
8864}
John McCall3969e302009-12-08 07:46:18 +00008865
John McCall84d87672009-12-10 09:41:52 +00008866/// Hides a using shadow declaration. This is required by the current
8867/// using-decl implementation when a resolvable using declaration in a
8868/// class is followed by a declaration which would hide or override
8869/// one or more of the using decl's targets; for example:
8870///
8871/// struct Base { void foo(int); };
8872/// struct Derived : Base {
8873/// using Base::foo;
8874/// void foo(int);
8875/// };
8876///
8877/// The governing language is C++03 [namespace.udecl]p12:
8878///
8879/// When a using-declaration brings names from a base class into a
8880/// derived class scope, member functions in the derived class
8881/// override and/or hide member functions with the same name and
8882/// parameter types in a base class (rather than conflicting).
8883///
8884/// There are two ways to implement this:
8885/// (1) optimistically create shadow decls when they're not hidden
8886/// by existing declarations, or
8887/// (2) don't create any shadow decls (or at least don't make them
8888/// visible) until we've fully parsed/instantiated the class.
8889/// The problem with (1) is that we might have to retroactively remove
8890/// a shadow decl, which requires several O(n) operations because the
8891/// decl structures are (very reasonably) not designed for removal.
8892/// (2) avoids this but is very fiddly and phase-dependent.
8893void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00008894 if (Shadow->getDeclName().getNameKind() ==
8895 DeclarationName::CXXConversionFunctionName)
8896 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8897
John McCall84d87672009-12-10 09:41:52 +00008898 // Remove it from the DeclContext...
8899 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008900
John McCall84d87672009-12-10 09:41:52 +00008901 // ...and the scope, if applicable...
8902 if (S) {
John McCall48871652010-08-21 09:40:31 +00008903 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00008904 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008905 }
8906
John McCall84d87672009-12-10 09:41:52 +00008907 // ...and the using decl.
8908 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8909
8910 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00008911 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00008912}
8913
Richard Smith09d5b3a2014-05-01 00:35:04 +00008914/// Find the base specifier for a base class with the given type.
8915static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8916 QualType DesiredBase,
8917 bool &AnyDependentBases) {
8918 // Check whether the named type is a direct base class.
8919 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8920 for (auto &Base : Derived->bases()) {
8921 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8922 if (CanonicalDesiredBase == BaseType)
8923 return &Base;
8924 if (BaseType->isDependentType())
8925 AnyDependentBases = true;
8926 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008927 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008928}
8929
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008930namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008931class UsingValidatorCCC : public CorrectionCandidateCallback {
8932public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00008933 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008934 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008935 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00008936 IsInstantiation(IsInstantiation), OldNNS(NNS),
8937 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008938
Craig Toppera798a9d2014-03-02 09:32:10 +00008939 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008940 NamedDecl *ND = Candidate.getCorrectionDecl();
8941
8942 // Keywords are not valid here.
8943 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008944 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008945
8946 // Completely unqualified names are invalid for a 'using' declaration.
8947 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8948 return false;
8949
Richard Smith9385d702016-05-14 01:58:49 +00008950 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8951 // reject.
8952
Richard Smith09d5b3a2014-05-01 00:35:04 +00008953 if (RequireMemberOf) {
8954 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8955 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8956 // No-one ever wants a using-declaration to name an injected-class-name
8957 // of a base class, unless they're declaring an inheriting constructor.
8958 ASTContext &Ctx = ND->getASTContext();
8959 if (!Ctx.getLangOpts().CPlusPlus11)
8960 return false;
8961 QualType FoundType = Ctx.getRecordType(FoundRecord);
8962
8963 // Check that the injected-class-name is named as a member of its own
8964 // type; we don't want to suggest 'using Derived::Base;', since that
8965 // means something else.
8966 NestedNameSpecifier *Specifier =
8967 Candidate.WillReplaceSpecifier()
8968 ? Candidate.getCorrectionSpecifier()
8969 : OldNNS;
8970 if (!Specifier->getAsType() ||
8971 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8972 return false;
8973
8974 // Check that this inheriting constructor declaration actually names a
8975 // direct base class of the current class.
8976 bool AnyDependentBases = false;
8977 if (!findDirectBaseWithType(RequireMemberOf,
8978 Ctx.getRecordType(FoundRecord),
8979 AnyDependentBases) &&
8980 !AnyDependentBases)
8981 return false;
8982 } else {
8983 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8984 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8985 return false;
8986
8987 // FIXME: Check that the base class member is accessible?
8988 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00008989 } else {
8990 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8991 if (FoundRecord && FoundRecord->isInjectedClassName())
8992 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008993 }
8994
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008995 if (isa<TypeDecl>(ND))
8996 return HasTypenameKeyword || !IsInstantiation;
8997
8998 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008999 }
9000
9001private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009002 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009003 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009004 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009005 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009006};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009007} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009008
John McCalle61f2ba2009-11-18 02:36:19 +00009009/// Builds a using declaration.
9010///
9011/// \param IsInstantiation - Whether this call arises from an
9012/// instantiation of an unresolved using declaration. We treat
9013/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009014NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9015 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009016 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009017 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009018 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00009019 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009020 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00009021 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009022 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009023 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009024 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009025
Anders Carlssonf038fc22009-08-28 05:49:21 +00009026 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009027
Anders Carlsson59140b32009-08-28 03:16:11 +00009028 if (SS.isEmpty()) {
9029 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00009030 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00009031 }
Mike Stump11289f42009-09-09 15:08:12 +00009032
Richard Smith5179eb72016-06-28 19:03:57 +00009033 // For an inheriting constructor declaration, the name of the using
9034 // declaration is the name of a constructor in this class, not in the
9035 // base class.
9036 DeclarationNameInfo UsingName = NameInfo;
9037 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9038 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9039 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9040 Context.getCanonicalType(Context.getRecordType(RD))));
9041
John McCall84d87672009-12-10 09:41:52 +00009042 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009043 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009044 ForRedeclaration);
9045 Previous.setHideTags(false);
9046 if (S) {
9047 LookupName(Previous, S);
9048
9049 // It is really dumb that we have to do this.
9050 LookupResult::Filter F = Previous.makeFilter();
9051 while (F.hasNext()) {
9052 NamedDecl *D = F.next();
9053 if (!isDeclInScope(D, CurContext, S))
9054 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009055 // If we found a local extern declaration that's not ordinarily visible,
9056 // and this declaration is being added to a non-block scope, ignore it.
9057 // We're only checking for scope conflicts here, not also for violations
9058 // of the linkage rules.
9059 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9060 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9061 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009062 }
9063 F.done();
9064 } else {
9065 assert(IsInstantiation && "no scope in non-instantiation");
9066 assert(CurContext->isRecord() && "scope not record in instantiation");
9067 LookupQualifiedName(Previous, CurContext);
9068 }
9069
John McCall84d87672009-12-10 09:41:52 +00009070 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009071 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9072 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009073 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009074
9075 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00009076 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009077 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009078
John McCall84c16cf2009-11-12 03:15:40 +00009079 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009080 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009081 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00009082 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009083 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009084 // FIXME: not all declaration name kinds are legal here
9085 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9086 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009087 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009088 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00009089 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009090 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9091 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00009092 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009093 D->setAccess(AS);
9094 CurContext->addDecl(D);
9095 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009096 }
John McCallb96ec562009-12-04 22:46:56 +00009097
Richard Smith09d5b3a2014-05-01 00:35:04 +00009098 auto Build = [&](bool Invalid) {
9099 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009100 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9101 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009102 UD->setAccess(AS);
9103 CurContext->addDecl(UD);
9104 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009105 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009106 };
9107 auto BuildInvalid = [&]{ return Build(true); };
9108 auto BuildValid = [&]{ return Build(false); };
9109
9110 if (RequireCompleteDeclContext(SS, LookupContext))
9111 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009112
Richard Smith78163e22015-04-01 19:31:06 +00009113 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009114 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009115
John McCall3969e302009-12-08 07:46:18 +00009116 // Unlike most lookups, we don't always want to hide tag
9117 // declarations: tag names are visible through the using declaration
9118 // even if hidden by ordinary names, *except* in a dependent context
9119 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009120 if (!IsInstantiation)
9121 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009122
John McCall5dadb652012-04-07 03:04:20 +00009123 // For the purposes of this lookup, we have a base object type
9124 // equal to that of the current context.
9125 if (CurContext->isRecord()) {
9126 R.setBaseObjectType(
9127 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9128 }
9129
John McCall27b18f82009-11-17 02:14:36 +00009130 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009131
Richard Smith78163e22015-04-01 19:31:06 +00009132 // Try to correct typos if possible. If constructor name lookup finds no
9133 // results, that means the named class has no explicit constructors, and we
9134 // suppressed declaring implicit ones (probably because it's dependent or
9135 // invalid).
9136 if (R.empty() &&
9137 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009138 if (TypoCorrection Corrected = CorrectTypo(
9139 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9140 llvm::make_unique<UsingValidatorCCC>(
9141 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9142 dyn_cast<CXXRecordDecl>(CurContext)),
9143 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009144 // We reject any correction for which ND would be NULL.
9145 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009146
Richard Smithf9b15102013-08-17 00:46:16 +00009147 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009148 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009149 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9150 << NameInfo.getName() << LookupContext << 0
9151 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009152
9153 // If we corrected to an inheriting constructor, handle it as one.
9154 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9155 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009156 // The parent of the injected class name is the class itself.
9157 RD = cast<CXXRecordDecl>(RD->getParent());
9158
Richard Smith09d5b3a2014-05-01 00:35:04 +00009159 // Fix up the information we'll use to build the using declaration.
9160 if (Corrected.WillReplaceSpecifier()) {
9161 NestedNameSpecifierLocBuilder Builder;
9162 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9163 QualifierLoc.getSourceRange());
9164 QualifierLoc = Builder.getWithLocInContext(Context);
9165 }
9166
Richard Smith5179eb72016-06-28 19:03:57 +00009167 // In this case, the name we introduce is the name of a derived class
9168 // constructor.
9169 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9170 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9171 Context.getCanonicalType(Context.getRecordType(CurClass))));
9172 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009173 for (auto *Ctor : LookupConstructors(RD))
9174 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009175 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009176 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009177 // FIXME: Pick up all the declarations if we found an overloaded
9178 // function.
9179 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009180 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009181 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009182 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009183 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009184 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009185 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009186 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009187 }
9188
Richard Smith09d5b3a2014-05-01 00:35:04 +00009189 if (R.isAmbiguous())
9190 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009191
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009192 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009193 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009194 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009195 Diag(IdentLoc, diag::err_using_typename_non_type);
9196 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9197 Diag((*I)->getUnderlyingDecl()->getLocation(),
9198 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009199 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009200 }
9201 } else {
9202 // If we asked for a non-typename and we got a type, error out,
9203 // but only if this is an instantiation of an unresolved using
9204 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009205 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009206 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9207 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009208 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009209 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009210 }
9211
Richard Smith5cbeb752016-05-05 02:13:49 +00009212 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009213 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009214 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009215 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9216 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009217 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009218 }
Mike Stump11289f42009-09-09 15:08:12 +00009219
Richard Smith5cbeb752016-05-05 02:13:49 +00009220 // C++14 [namespace.udecl]p7:
9221 // A using-declaration shall not name a scoped enumerator.
9222 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9223 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9224 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9225 << SS.getRange();
9226 return BuildInvalid();
9227 }
9228 }
9229
Richard Smith09d5b3a2014-05-01 00:35:04 +00009230 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009231
Richard Smith5179eb72016-06-28 19:03:57 +00009232 // Some additional rules apply to inheriting constructors.
9233 if (UsingName.getName().getNameKind() ==
9234 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009235 // Suppress access diagnostics; the access check is instead performed at the
9236 // point of use for an inheriting constructor.
9237 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009238 if (CheckInheritingConstructorUsingDecl(UD))
9239 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009240 }
9241
John McCall84d87672009-12-10 09:41:52 +00009242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009243 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009244 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9245 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009246 }
John McCall3f746822009-11-17 05:59:44 +00009247
9248 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009249}
9250
Sebastian Redl08905022011-02-05 19:23:19 +00009251/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009252bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009253 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009254
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009255 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009256 assert(SourceType &&
9257 "Using decl naming constructor doesn't have type in scope spec.");
9258 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9259
9260 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009261 bool AnyDependentBases = false;
9262 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9263 AnyDependentBases);
9264 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009265 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009266 diag::err_using_decl_constructor_not_in_direct_base)
9267 << UD->getNameInfo().getSourceRange()
9268 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009269 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009270 return true;
9271 }
9272
Richard Smith09d5b3a2014-05-01 00:35:04 +00009273 if (Base)
9274 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009275
9276 return false;
9277}
9278
John McCall84d87672009-12-10 09:41:52 +00009279/// Checks that the given using declaration is not an invalid
9280/// redeclaration. Note that this is checking only for the using decl
9281/// itself, not for any ill-formedness among the UsingShadowDecls.
9282bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009283 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009284 const CXXScopeSpec &SS,
9285 SourceLocation NameLoc,
9286 const LookupResult &Prev) {
9287 // C++03 [namespace.udecl]p8:
9288 // C++0x [namespace.udecl]p10:
9289 // A using-declaration is a declaration and can therefore be used
9290 // repeatedly where (and only where) multiple declarations are
9291 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009292 //
John McCall032092f2010-11-29 18:01:58 +00009293 // That's in non-member contexts.
9294 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00009295 return false;
9296
Aaron Ballman4a979672014-01-03 13:56:08 +00009297 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00009298
9299 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9300 NamedDecl *D = *I;
9301
9302 bool DTypename;
9303 NestedNameSpecifier *DQual;
9304 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009305 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009306 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009307 } else if (UnresolvedUsingValueDecl *UD
9308 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9309 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009310 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009311 } else if (UnresolvedUsingTypenameDecl *UD
9312 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9313 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009314 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009315 } else continue;
9316
9317 // using decls differ if one says 'typename' and the other doesn't.
9318 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009319 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009320
9321 // using decls differ if they name different scopes (but note that
9322 // template instantiation can cause this check to trigger when it
9323 // didn't before instantiation).
9324 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9325 Context.getCanonicalNestedNameSpecifier(DQual))
9326 continue;
9327
9328 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009329 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009330 return true;
9331 }
9332
9333 return false;
9334}
9335
John McCall3969e302009-12-08 07:46:18 +00009336
John McCallb96ec562009-12-04 22:46:56 +00009337/// Checks that the given nested-name qualifier used in a using decl
9338/// in the current context is appropriately related to the current
9339/// scope. If an error is found, diagnoses it and returns true.
9340bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9341 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009342 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009343 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009344 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009345
John McCall3969e302009-12-08 07:46:18 +00009346 if (!CurContext->isRecord()) {
9347 // C++03 [namespace.udecl]p3:
9348 // C++0x [namespace.udecl]p8:
9349 // A using-declaration for a class member shall be a member-declaration.
9350
9351 // If we weren't able to compute a valid scope, it must be a
9352 // dependent class scope.
Richard Smith5cbeb752016-05-05 02:13:49 +00009353 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9354 auto *RD = NamedContext
9355 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9356 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009357 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009358 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009359
John McCall3969e302009-12-08 07:46:18 +00009360 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9361 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009362
9363 // If we have a complete, non-dependent source type, try to suggest a
9364 // way to get the same effect.
9365 if (!RD)
9366 return true;
9367
9368 // Find what this using-declaration was referring to.
9369 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9370 R.setHideTags(false);
9371 R.suppressDiagnostics();
9372 LookupQualifiedName(R, RD);
9373
9374 if (R.getAsSingle<TypeDecl>()) {
9375 if (getLangOpts().CPlusPlus11) {
9376 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9377 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9378 << 0 // alias declaration
9379 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9380 NameInfo.getName().getAsString() +
9381 " = ");
9382 } else {
9383 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9384 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009385 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009386 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9387 << 1 // typedef declaration
9388 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9389 << FixItHint::CreateInsertion(
9390 InsertLoc, " " + NameInfo.getName().getAsString());
9391 }
9392 } else if (R.getAsSingle<VarDecl>()) {
9393 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9394 // repeating the type of the static data member here.
9395 FixItHint FixIt;
9396 if (getLangOpts().CPlusPlus11) {
9397 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9398 FixIt = FixItHint::CreateReplacement(
9399 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9400 }
9401
9402 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9403 << 2 // reference declaration
9404 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009405 } else if (R.getAsSingle<EnumConstantDecl>()) {
9406 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9407 // repeating the type of the enumeration here, and we can't do so if
9408 // the type is anonymous.
9409 FixItHint FixIt;
9410 if (getLangOpts().CPlusPlus11) {
9411 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9412 FixIt = FixItHint::CreateReplacement(
9413 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9414 }
9415
9416 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9417 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9418 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009419 }
John McCall3969e302009-12-08 07:46:18 +00009420 return true;
9421 }
9422
9423 // Otherwise, everything is known to be fine.
9424 return false;
9425 }
9426
9427 // The current scope is a record.
9428
9429 // If the named context is dependent, we can't decide much.
9430 if (!NamedContext) {
9431 // FIXME: in C++0x, we can diagnose if we can prove that the
9432 // nested-name-specifier does not refer to a base class, which is
9433 // still possible in some cases.
9434
9435 // Otherwise we have to conservatively report that things might be
9436 // okay.
9437 return false;
9438 }
9439
9440 if (!NamedContext->isRecord()) {
9441 // Ideally this would point at the last name in the specifier,
9442 // but we don't have that level of source info.
9443 Diag(SS.getRange().getBegin(),
9444 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009445 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009446 return true;
9447 }
9448
Douglas Gregor7c842292010-12-21 07:41:49 +00009449 if (!NamedContext->isDependentContext() &&
9450 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9451 return true;
9452
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009453 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009454 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009455 // In a using-declaration used as a member-declaration, the
9456 // nested-name-specifier shall name a base class of the class
9457 // being defined.
9458
9459 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9460 cast<CXXRecordDecl>(NamedContext))) {
9461 if (CurContext == NamedContext) {
9462 Diag(NameLoc,
9463 diag::err_using_decl_nested_name_specifier_is_current_class)
9464 << SS.getRange();
9465 return true;
9466 }
9467
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009468 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9469 Diag(SS.getRange().getBegin(),
9470 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9471 << SS.getScopeRep()
9472 << cast<CXXRecordDecl>(CurContext)
9473 << SS.getRange();
9474 }
John McCall3969e302009-12-08 07:46:18 +00009475 return true;
9476 }
9477
9478 return false;
9479 }
9480
9481 // C++03 [namespace.udecl]p4:
9482 // A using-declaration used as a member-declaration shall refer
9483 // to a member of a base class of the class being defined [etc.].
9484
9485 // Salient point: SS doesn't have to name a base class as long as
9486 // lookup only finds members from base classes. Therefore we can
9487 // diagnose here only if we can prove that that can't happen,
9488 // i.e. if the class hierarchies provably don't intersect.
9489
9490 // TODO: it would be nice if "definitely valid" results were cached
9491 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9492 // need to be repeated.
9493
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009494 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9495 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9496 Bases.insert(Base);
9497 return true;
John McCall3969e302009-12-08 07:46:18 +00009498 };
9499
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009500 // Collect all bases. Return false if we find a dependent base.
9501 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009502 return false;
9503
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009504 // Returns true if the base is dependent or is one of the accumulated base
9505 // classes.
9506 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9507 return !Bases.count(Base);
9508 };
9509
9510 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009511 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009512 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9513 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009514 return false;
9515
9516 Diag(SS.getRange().getBegin(),
9517 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009518 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009519 << cast<CXXRecordDecl>(CurContext)
9520 << SS.getRange();
9521
9522 return true;
John McCallb96ec562009-12-04 22:46:56 +00009523}
9524
Richard Smithdda56e42011-04-15 14:24:37 +00009525Decl *Sema::ActOnAliasDeclaration(Scope *S,
9526 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009527 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009528 SourceLocation UsingLoc,
9529 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009530 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009531 TypeResult Type,
9532 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009533 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009534 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009535 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009536 assert((S->getFlags() & Scope::DeclScope) &&
9537 "got alias-declaration outside of declaration scope");
9538
9539 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009540 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009541
9542 bool Invalid = false;
9543 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009544 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009545 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009546
9547 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009548 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009549
9550 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009551 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009552 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009553 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9554 TInfo->getTypeLoc().getBeginLoc());
9555 }
Richard Smithdda56e42011-04-15 14:24:37 +00009556
9557 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9558 LookupName(Previous, S);
9559
9560 // Warn about shadowing the name of a template parameter.
9561 if (Previous.isSingleResult() &&
9562 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009563 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009564 Previous.clear();
9565 }
9566
9567 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9568 "name in alias declaration must be an identifier");
9569 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9570 Name.StartLocation,
9571 Name.Identifier, TInfo);
9572
9573 NewTD->setAccess(AS);
9574
9575 if (Invalid)
9576 NewTD->setInvalidDecl();
9577
Richard Smith54ecd982013-02-20 19:22:51 +00009578 ProcessDeclAttributeList(S, NewTD, AttrList);
9579
Richard Smith3f1b5d02011-05-05 21:57:07 +00009580 CheckTypedefForVariablyModifiedType(S, NewTD);
9581 Invalid |= NewTD->isInvalidDecl();
9582
Richard Smithdda56e42011-04-15 14:24:37 +00009583 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009584
9585 NamedDecl *NewND;
9586 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009587 TypeAliasTemplateDecl *OldDecl = nullptr;
9588 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009589
9590 if (TemplateParamLists.size() != 1) {
9591 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009592 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9593 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009594 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009595 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009596
Richard Smith882593f2016-04-06 17:38:58 +00009597 // Check that we can declare a template here.
9598 if (CheckTemplateDeclScope(S, TemplateParams))
9599 return nullptr;
9600
Richard Smith3f1b5d02011-05-05 21:57:07 +00009601 // Only consider previous declarations in the same scope.
9602 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9603 /*ExplicitInstantiationOrSpecialization*/false);
9604 if (!Previous.empty()) {
9605 Redeclaration = true;
9606
9607 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9608 if (!OldDecl && !Invalid) {
9609 Diag(UsingLoc, diag::err_redefinition_different_kind)
9610 << Name.Identifier;
9611
9612 NamedDecl *OldD = Previous.getRepresentativeDecl();
9613 if (OldD->getLocation().isValid())
9614 Diag(OldD->getLocation(), diag::note_previous_definition);
9615
9616 Invalid = true;
9617 }
9618
9619 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9620 if (TemplateParameterListsAreEqual(TemplateParams,
9621 OldDecl->getTemplateParameters(),
9622 /*Complain=*/true,
9623 TPL_TemplateMatch))
9624 OldTemplateParams = OldDecl->getTemplateParameters();
9625 else
9626 Invalid = true;
9627
9628 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9629 if (!Invalid &&
9630 !Context.hasSameType(OldTD->getUnderlyingType(),
9631 NewTD->getUnderlyingType())) {
9632 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9633 // but we can't reasonably accept it.
9634 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9635 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9636 if (OldTD->getLocation().isValid())
9637 Diag(OldTD->getLocation(), diag::note_previous_definition);
9638 Invalid = true;
9639 }
9640 }
9641 }
9642
9643 // Merge any previous default template arguments into our parameters,
9644 // and check the parameter list.
9645 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9646 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00009647 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009648
9649 TypeAliasTemplateDecl *NewDecl =
9650 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9651 Name.Identifier, TemplateParams,
9652 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00009653 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009654
9655 NewDecl->setAccess(AS);
9656
9657 if (Invalid)
9658 NewDecl->setInvalidDecl();
9659 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00009660 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009661
9662 NewND = NewDecl;
9663 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00009664 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9665 setTagNameForLinkagePurposes(TD, NewTD);
9666 handleTagNumbering(TD, S);
9667 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00009668 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9669 NewND = NewTD;
9670 }
Richard Smithdda56e42011-04-15 14:24:37 +00009671
Richard Smith3cbf3f12016-07-15 20:53:25 +00009672 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00009673 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009674 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00009675}
9676
Richard Smithf4634362014-09-03 23:11:22 +00009677Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9678 SourceLocation AliasLoc,
9679 IdentifierInfo *Alias, CXXScopeSpec &SS,
9680 SourceLocation IdentLoc,
9681 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00009682
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009683 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00009684 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9685 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009686
John McCall27b18f82009-11-17 02:14:36 +00009687 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00009688 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009689
John McCall9f3059a2009-10-09 21:13:30 +00009690 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00009691 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00009692 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00009693 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00009694 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00009695 }
Richard Smithf4634362014-09-03 23:11:22 +00009696 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00009697 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00009698
9699 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00009700 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9701 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00009702 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00009703
Richard Smith2b2a1762015-12-03 23:24:04 +00009704 // Check we're not shadowing a template parameter.
9705 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9706 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9707 PrevR.clear();
9708 }
Aaron Ballman43f40102014-11-14 22:34:56 +00009709
Richard Smith2b2a1762015-12-03 23:24:04 +00009710 // Filter out any other lookup result from an enclosing scope.
9711 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9712 /*AllowInlineNamespace*/false);
9713
9714 // Find the previous declaration and check that we can redeclare it.
9715 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00009716 if (PrevR.isSingleResult()) {
9717 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9718 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009719 // We already have an alias with the same name that points to the same
9720 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00009721 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9722 Prev = AD;
9723 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009724 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9725 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +00009726 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +00009727 << AD->getNamespace();
9728 return nullptr;
9729 }
Richard Smith2b2a1762015-12-03 23:24:04 +00009730 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +00009731 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +00009732 ? diag::err_redefinition
9733 : diag::err_redefinition_different_kind;
9734 Diag(AliasLoc, DiagID) << Alias;
9735 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9736 return nullptr;
9737 }
9738 }
Mike Stump11289f42009-09-09 15:08:12 +00009739
Nico Riecke50e59a2014-11-24 17:29:52 +00009740 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00009741 DiagnoseUseOfDecl(ND, IdentLoc);
9742
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009743 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00009744 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00009745 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00009746 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00009747 if (Prev)
9748 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00009749
John McCalld8d0d432010-02-16 06:53:13 +00009750 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00009751 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00009752}
9753
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009754Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009755Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9756 CXXMethodDecl *MD) {
9757 CXXRecordDecl *ClassDecl = MD->getParent();
9758
Douglas Gregor6d880b12010-07-01 22:31:05 +00009759 // C++ [except.spec]p14:
9760 // An implicitly declared special member function (Clause 12) shall have an
9761 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00009762 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009763 if (ClassDecl->isInvalidDecl())
9764 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00009765
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009766 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009767 for (const auto &B : ClassDecl->bases()) {
9768 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00009769 continue;
9770
Aaron Ballman574705e2014-03-13 15:41:46 +00009771 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009772 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009773 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9774 // If this is a deleted function, add it anyway. This might be conformant
9775 // with the standard. This might not. I'm not sure. It might not matter.
9776 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00009777 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009778 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009779 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009780
9781 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009782 for (const auto &B : ClassDecl->vbases()) {
9783 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009784 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009785 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9786 // If this is a deleted function, add it anyway. This might be conformant
9787 // with the standard. This might not. I'm not sure. It might not matter.
9788 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009789 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009790 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009791 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009792
9793 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009794 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00009795 if (F->hasInClassInitializer()) {
9796 if (Expr *E = F->getInClassInitializer())
9797 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00009798 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00009799 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00009800 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9801 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9802 // If this is a deleted function, add it anyway. This might be conformant
9803 // with the standard. This might not. I'm not sure. It might not matter.
9804 // In particular, the problem is that this function never gets called. It
9805 // might just be ill-formed because this function attempts to refer to
9806 // a deleted function here.
9807 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009808 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009809 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009810 }
John McCalldb40c7f2010-12-14 08:05:40 +00009811
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009812 return ExceptSpec;
9813}
9814
Richard Smithc2bc61b2013-03-18 21:12:30 +00009815Sema::ImplicitExceptionSpecification
Richard Smith5179eb72016-06-28 19:03:57 +00009816Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9817 CXXConstructorDecl *CD) {
Richard Smithb7151b92013-04-10 06:11:48 +00009818 CXXRecordDecl *ClassDecl = CD->getParent();
9819
9820 // C++ [except.spec]p14:
9821 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00009822 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00009823 if (ClassDecl->isInvalidDecl())
9824 return ExceptSpec;
9825
Richard Smith5179eb72016-06-28 19:03:57 +00009826 auto Inherited = CD->getInheritedConstructor();
9827 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
Richard Smithb7151b92013-04-10 06:11:48 +00009828
Richard Smith5179eb72016-06-28 19:03:57 +00009829 // Direct and virtual base-class constructors.
9830 for (bool VBase : {false, true}) {
9831 for (CXXBaseSpecifier &B :
9832 VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9833 // Don't visit direct vbases twice.
9834 if (B.isVirtual() != VBase)
Richard Smithb7151b92013-04-10 06:11:48 +00009835 continue;
Richard Smithb7151b92013-04-10 06:11:48 +00009836
Richard Smith5179eb72016-06-28 19:03:57 +00009837 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9838 if (!BaseClass)
Richard Smithb7151b92013-04-10 06:11:48 +00009839 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00009840
9841 CXXConstructorDecl *Constructor =
9842 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9843 .first;
9844 if (!Constructor)
9845 Constructor = LookupDefaultConstructor(BaseClass);
Richard Smithb7151b92013-04-10 06:11:48 +00009846 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009847 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00009848 }
9849 }
9850
9851 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009852 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00009853 if (F->hasInClassInitializer()) {
9854 if (Expr *E = F->getInClassInitializer())
9855 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00009856 } else if (const RecordType *RecordTy
9857 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9858 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9859 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9860 if (Constructor)
9861 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9862 }
9863 }
9864
Richard Smithc2bc61b2013-03-18 21:12:30 +00009865 return ExceptSpec;
9866}
9867
Richard Smith8bf22e52012-11-29 01:34:07 +00009868namespace {
9869/// RAII object to register a special member as being currently declared.
9870struct DeclaringSpecialMember {
9871 Sema &S;
9872 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +00009873 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +00009874 bool WasAlreadyBeingDeclared;
9875
9876 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +00009877 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +00009878 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00009879 if (WasAlreadyBeingDeclared)
9880 // This almost never happens, but if it does, ensure that our cache
9881 // doesn't contain a stale result.
9882 S.SpecialMemberCache.clear();
9883
9884 // FIXME: Register a note to be produced if we encounter an error while
9885 // declaring the special member.
9886 }
9887 ~DeclaringSpecialMember() {
9888 if (!WasAlreadyBeingDeclared)
9889 S.SpecialMembersBeingDeclared.erase(D);
9890 }
9891
9892 /// \brief Are we already trying to declare this special member?
9893 bool isAlreadyBeingDeclared() const {
9894 return WasAlreadyBeingDeclared;
9895 }
9896};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009897}
Richard Smith8bf22e52012-11-29 01:34:07 +00009898
Richard Smith12e79312016-05-13 06:47:56 +00009899void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9900 // Look up any existing declarations, but don't trigger declaration of all
9901 // implicit special members with this name.
9902 DeclarationName Name = FD->getDeclName();
9903 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9904 ForRedeclaration);
9905 for (auto *D : FD->getParent()->lookup(Name))
9906 if (auto *Acceptable = R.getAcceptableDecl(D))
9907 R.addDecl(Acceptable);
9908 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +00009909 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +00009910
9911 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9912}
9913
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009914CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9915 CXXRecordDecl *ClassDecl) {
9916 // C++ [class.ctor]p5:
9917 // A default constructor for a class X is a constructor of class X
9918 // that can be called without an argument. If there is no
9919 // user-declared constructor for class X, a default constructor is
9920 // implicitly declared. An implicitly-declared default constructor
9921 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009922 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009923 "Should not build implicit default constructor!");
9924
Richard Smith8bf22e52012-11-29 01:34:07 +00009925 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9926 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009927 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009928
Richard Smithb5800092012-06-10 05:43:50 +00009929 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9930 CXXDefaultConstructor,
9931 false);
9932
Douglas Gregor6d880b12010-07-01 22:31:05 +00009933 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009934 CanQualType ClassType
9935 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009936 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009937 DeclarationName Name
9938 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009939 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00009940 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009941 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9942 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9943 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009944 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00009945 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009946
9947 if (getLangOpts().CUDA) {
9948 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9949 DefaultCon,
9950 /* ConstRHS */ false,
9951 /* Diagnose */ false);
9952 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009953
9954 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009955 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009956 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009957
Richard Smith6b02d462012-12-08 08:32:28 +00009958 // We don't need to use SpecialMemberIsTrivial here; triviality for default
9959 // constructors is easy to compute.
9960 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9961
Douglas Gregor9672f922010-07-03 00:47:00 +00009962 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00009963 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00009964
Richard Smith12e79312016-05-13 06:47:56 +00009965 Scope *S = getScopeForContext(ClassDecl);
9966 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9967
9968 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9969 SetDeclDeleted(DefaultCon, ClassLoc);
9970
9971 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +00009972 PushOnScopeChains(DefaultCon, S, false);
9973 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00009974
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009975 return DefaultCon;
9976}
9977
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009978void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9979 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009980 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009981 !Constructor->doesThisDeclarationHaveABody() &&
9982 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009983 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00009984
Anders Carlsson423f5d82010-04-23 16:04:08 +00009985 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00009986 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00009987
Eli Friedmaneaf34142012-10-18 20:14:08 +00009988 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009989 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00009990 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00009991 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009992 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009993 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00009994 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00009995 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00009996 }
Douglas Gregor73193272010-09-20 16:48:21 +00009997
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009998 // The exception specification is needed because we are defining the
9999 // function.
10000 ResolveExceptionSpec(CurrentLocation,
10001 Constructor->getType()->castAs<FunctionProtoType>());
10002
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010003 SourceLocation Loc = Constructor->getLocEnd().isValid()
10004 ? Constructor->getLocEnd()
10005 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010006 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010007
Eli Friedman276dd182013-09-05 00:02:25 +000010008 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010009 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010010
10011 if (ASTMutationListener *L = getASTMutationListener()) {
10012 L->CompletedImplicitDefinition(Constructor);
10013 }
Richard Trieuef64e942013-10-25 00:56:00 +000010014
10015 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010016}
10017
Richard Smith938f40b2011-06-11 17:19:42 +000010018void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010019 // Perform any delayed checks on exception specifications.
10020 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010021}
10022
Richard Smith5179eb72016-06-28 19:03:57 +000010023/// Find or create the fake constructor we synthesize to model constructing an
10024/// object of a derived class via a constructor of a base class.
10025CXXConstructorDecl *
10026Sema::findInheritingConstructor(SourceLocation Loc,
10027 CXXConstructorDecl *BaseCtor,
10028 ConstructorUsingShadowDecl *Shadow) {
10029 CXXRecordDecl *Derived = Shadow->getParent();
10030 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010031
Richard Smith5179eb72016-06-28 19:03:57 +000010032 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10033 // For now we use the name of the base class constructor as a member of the
10034 // derived class to indicate a (fake) inherited constructor name.
10035 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010036
Richard Smith5179eb72016-06-28 19:03:57 +000010037 // Check to see if we already have a fake constructor for this inherited
10038 // constructor call.
10039 for (NamedDecl *Ctor : Derived->lookup(Name))
10040 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10041 ->getInheritedConstructor()
10042 .getConstructor(),
10043 BaseCtor))
10044 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010045
Richard Smith5179eb72016-06-28 19:03:57 +000010046 DeclarationNameInfo NameInfo(Name, UsingLoc);
10047 TypeSourceInfo *TInfo =
10048 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10049 FunctionProtoTypeLoc ProtoLoc =
10050 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010051
Richard Smith5179eb72016-06-28 19:03:57 +000010052 // Check the inherited constructor is valid and find the list of base classes
10053 // from which it was inherited.
10054 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010055
Richard Smith5179eb72016-06-28 19:03:57 +000010056 bool Constexpr =
10057 BaseCtor->isConstexpr() &&
10058 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10059 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010060
Richard Smith5179eb72016-06-28 19:03:57 +000010061 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10062 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10063 BaseCtor->isExplicit(), /*Inline=*/true,
10064 /*ImplicitlyDeclared=*/true, Constexpr,
10065 InheritedConstructor(Shadow, BaseCtor));
10066 if (Shadow->isInvalidDecl())
10067 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010068
Richard Smith5179eb72016-06-28 19:03:57 +000010069 // Build an unevaluated exception specification for this fake constructor.
10070 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10071 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10072 EPI.ExceptionSpec.Type = EST_Unevaluated;
10073 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10074 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10075 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010076
Richard Smith5179eb72016-06-28 19:03:57 +000010077 // Build the parameter declarations.
10078 SmallVector<ParmVarDecl *, 16> ParamDecls;
10079 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010080 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010081 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10082 ParmVarDecl *PD = ParmVarDecl::Create(
10083 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10084 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10085 PD->setScopeInfo(0, I);
10086 PD->setImplicit();
10087 // Ensure attributes are propagated onto parameters (this matters for
10088 // format, pass_object_size, ...).
10089 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10090 ParamDecls.push_back(PD);
10091 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010092 }
10093
Richard Smith5179eb72016-06-28 19:03:57 +000010094 // Set up the new constructor.
10095 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10096 DerivedCtor->setAccess(BaseCtor->getAccess());
10097 DerivedCtor->setParams(ParamDecls);
10098 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010099
10100 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10101 SetDeclDeleted(DerivedCtor, UsingLoc);
10102
Richard Smith5179eb72016-06-28 19:03:57 +000010103 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010104}
10105
Richard Smith80a47022016-06-29 01:10:27 +000010106void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10107 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10108 Ctor->getInheritedConstructor().getShadowDecl());
10109 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10110 /*Diagnose*/true);
10111}
10112
Richard Smithc2bc61b2013-03-18 21:12:30 +000010113void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10114 CXXConstructorDecl *Constructor) {
10115 CXXRecordDecl *ClassDecl = Constructor->getParent();
10116 assert(Constructor->getInheritedConstructor() &&
10117 !Constructor->doesThisDeclarationHaveABody() &&
10118 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010119 if (Constructor->isInvalidDecl())
10120 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010121
Richard Smith5179eb72016-06-28 19:03:57 +000010122 ConstructorUsingShadowDecl *Shadow =
10123 Constructor->getInheritedConstructor().getShadowDecl();
10124 CXXConstructorDecl *InheritedCtor =
10125 Constructor->getInheritedConstructor().getConstructor();
10126
10127 // [class.inhctor.init]p1:
10128 // initialization proceeds as if a defaulted default constructor is used to
10129 // initialize the D object and each base class subobject from which the
10130 // constructor was inherited
10131
10132 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10133 CXXRecordDecl *RD = Shadow->getParent();
10134 SourceLocation InitLoc = Shadow->getLocation();
10135
10136 // Initializations are performed "as if by a defaulted default constructor",
10137 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010138 SynthesizedFunctionScope Scope(*this, Constructor);
10139 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010140
10141 // Build explicit initializers for all base classes from which the
10142 // constructor was inherited.
10143 SmallVector<CXXCtorInitializer*, 8> Inits;
10144 for (bool VBase : {false, true}) {
10145 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10146 if (B.isVirtual() != VBase)
10147 continue;
10148
10149 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10150 if (!BaseRD)
10151 continue;
10152
10153 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10154 if (!BaseCtor.first)
10155 continue;
10156
10157 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10158 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10159 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10160
10161 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10162 Inits.push_back(new (Context) CXXCtorInitializer(
10163 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10164 SourceLocation()));
10165 }
10166 }
10167
10168 // We now proceed as if for a defaulted default constructor, with the relevant
10169 // initializers replaced.
10170
10171 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10172 if (HadError || Trap.hasErrorOccurred()) {
10173 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010174 Constructor->setInvalidDecl();
10175 return;
10176 }
10177
Richard Smith5179eb72016-06-28 19:03:57 +000010178 // The exception specification is needed because we are defining the
10179 // function.
10180 ResolveExceptionSpec(CurrentLocation,
10181 Constructor->getType()->castAs<FunctionProtoType>());
10182
10183 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010184
Eli Friedman276dd182013-09-05 00:02:25 +000010185 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010186 MarkVTableUsed(CurrentLocation, ClassDecl);
10187
10188 if (ASTMutationListener *L = getASTMutationListener()) {
10189 L->CompletedImplicitDefinition(Constructor);
10190 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010191
Richard Smith5179eb72016-06-28 19:03:57 +000010192 DiagnoseUninitializedFields(*this, Constructor);
10193}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010194
Alexis Huntf91729462011-05-12 22:46:25 +000010195Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010196Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10197 CXXRecordDecl *ClassDecl = MD->getParent();
10198
Douglas Gregorf1203042010-07-01 19:09:28 +000010199 // C++ [except.spec]p14:
10200 // An implicitly declared special member function (Clause 12) shall have
10201 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +000010202 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010203 if (ClassDecl->isInvalidDecl())
10204 return ExceptSpec;
10205
Douglas Gregorf1203042010-07-01 19:09:28 +000010206 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010207 for (const auto &B : ClassDecl->bases()) {
10208 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +000010209 continue;
10210
Aaron Ballman574705e2014-03-13 15:41:46 +000010211 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10212 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010213 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010214 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010215
Douglas Gregorf1203042010-07-01 19:09:28 +000010216 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010217 for (const auto &B : ClassDecl->vbases()) {
10218 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10219 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010220 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010221 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010222
Douglas Gregorf1203042010-07-01 19:09:28 +000010223 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010224 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +000010225 if (const RecordType *RecordTy
10226 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +000010227 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010228 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010229 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010230
Alexis Huntf91729462011-05-12 22:46:25 +000010231 return ExceptSpec;
10232}
10233
10234CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10235 // C++ [class.dtor]p2:
10236 // If a class has no user-declared destructor, a destructor is
10237 // declared implicitly. An implicitly-declared destructor is an
10238 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010239 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010240
Richard Smith8bf22e52012-11-29 01:34:07 +000010241 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10242 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010243 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010244
Douglas Gregor7454c562010-07-02 20:37:36 +000010245 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010246 CanQualType ClassType
10247 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010248 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010249 DeclarationName Name
10250 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010251 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010252 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010253 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010254 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010255 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010256 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010257 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010258
10259 if (getLangOpts().CUDA) {
10260 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10261 Destructor,
10262 /* ConstRHS */ false,
10263 /* Diagnose */ false);
10264 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010265
10266 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010267 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010268 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010269
Richard Smith6b02d462012-12-08 08:32:28 +000010270 // We don't need to use SpecialMemberIsTrivial here; triviality for
10271 // destructors is easy to compute.
10272 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10273
Douglas Gregor7454c562010-07-02 20:37:36 +000010274 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010275 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010276
Richard Smith12e79312016-05-13 06:47:56 +000010277 Scope *S = getScopeForContext(ClassDecl);
10278 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10279
Richard Smithb2f0f052016-10-10 18:54:32 +000010280 // We can't check whether an implicit destructor is deleted before we complete
10281 // the definition of the class, because its validity depends on the alignment
10282 // of the class. We'll check this from ActOnFields once the class is complete.
10283 if (ClassDecl->isCompleteDefinition() &&
10284 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010285 SetDeclDeleted(Destructor, ClassLoc);
10286
Douglas Gregor7454c562010-07-02 20:37:36 +000010287 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010288 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010289 PushOnScopeChains(Destructor, S, false);
10290 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010291
Douglas Gregorf1203042010-07-01 19:09:28 +000010292 return Destructor;
10293}
10294
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010295void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010296 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010297 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010298 !Destructor->doesThisDeclarationHaveABody() &&
10299 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010300 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010301 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010302 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010303
Douglas Gregor54818f02010-05-12 16:39:35 +000010304 if (Destructor->isInvalidDecl())
10305 return;
10306
Eli Friedmaneaf34142012-10-18 20:14:08 +000010307 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010308
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010309 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010310 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10311 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010312
Douglas Gregor54818f02010-05-12 16:39:35 +000010313 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010314 Diag(CurrentLocation, diag::note_member_synthesized_at)
10315 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10316
10317 Destructor->setInvalidDecl();
10318 return;
10319 }
10320
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010321 // The exception specification is needed because we are defining the
10322 // function.
10323 ResolveExceptionSpec(CurrentLocation,
10324 Destructor->getType()->castAs<FunctionProtoType>());
10325
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010326 SourceLocation Loc = Destructor->getLocEnd().isValid()
10327 ? Destructor->getLocEnd()
10328 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010329 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010330 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010331 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010332
10333 if (ASTMutationListener *L = getASTMutationListener()) {
10334 L->CompletedImplicitDefinition(Destructor);
10335 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010336}
10337
Richard Smith84973e52012-04-21 18:42:51 +000010338/// \brief Perform any semantic analysis which needs to be delayed until all
10339/// pending class member declarations have been parsed.
10340void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010341 // If the context is an invalid C++ class, just suppress these checks.
10342 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10343 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010344 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010345 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010346 return;
10347 }
10348 }
Richard Smith84973e52012-04-21 18:42:51 +000010349}
10350
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010351static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10352 // Don't do anything for template patterns.
10353 if (Class->getDescribedClassTemplate())
10354 return;
10355
David Majnemer474b3232015-12-31 05:36:46 +000010356 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10357 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10358
10359 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010360 for (Decl *Member : Class->decls()) {
10361 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10362 if (!CD) {
10363 // Recurse on nested classes.
10364 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10365 getDefaultArgExprsForConstructors(S, NestedRD);
10366 continue;
10367 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10368 continue;
10369 }
10370
David Majnemer474b3232015-12-31 05:36:46 +000010371 CallingConv ActualCallingConv =
10372 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10373
10374 // Skip default constructors with typical calling conventions and no default
10375 // arguments.
10376 unsigned NumParams = CD->getNumParams();
10377 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10378 continue;
10379
10380 if (LastExportedDefaultCtor) {
10381 S.Diag(LastExportedDefaultCtor->getLocation(),
10382 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10383 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10384 << CD->getDeclName();
10385 return;
10386 }
10387 LastExportedDefaultCtor = CD;
10388
10389 for (unsigned I = 0; I != NumParams; ++I) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010390 // Skip any default arguments that we've already instantiated.
10391 if (S.Context.getDefaultArgExprForConstructor(CD, I))
10392 continue;
10393
10394 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10395 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +000010396 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010397 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10398 }
10399 }
10400}
10401
Hans Wennborg99000c22015-08-15 01:18:16 +000010402void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010403 auto *RD = dyn_cast<CXXRecordDecl>(D);
10404
10405 // Default constructors that are annotated with __declspec(dllexport) which
10406 // have default arguments or don't use the standard calling convention are
10407 // wrapped with a thunk called the default constructor closure.
10408 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10409 getDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +000010410
Reid Kleckner5b640342016-02-26 19:51:02 +000010411 referenceDLLExportedClassMethods();
10412}
10413
10414void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010415 if (!DelayedDllExportClasses.empty()) {
10416 // Calling ReferenceDllExportedMethods might cause the current function to
10417 // be called again, so use a local copy of DelayedDllExportClasses.
10418 SmallVector<CXXRecordDecl *, 4> WorkList;
10419 std::swap(DelayedDllExportClasses, WorkList);
10420 for (CXXRecordDecl *Class : WorkList)
10421 ReferenceDllExportedMethods(*this, Class);
10422 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010423}
10424
Richard Smithd3b5c9082012-07-27 04:22:15 +000010425void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10426 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010427 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010428 "adjusting dtor exception specs was introduced in c++11");
10429
Sebastian Redl623ea822011-05-19 05:13:44 +000010430 // C++11 [class.dtor]p3:
10431 // A declaration of a destructor that does not have an exception-
10432 // specification is implicitly considered to have the same exception-
10433 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010434 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010435 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010436 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010437 return;
10438
Chandler Carruth9a797572011-09-20 04:55:26 +000010439 // Replace the destructor's type, building off the existing one. Fortunately,
10440 // the only thing of interest in the destructor type is its extended info.
10441 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010442 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010443 EPI.ExceptionSpec.Type = EST_Unevaluated;
10444 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010445 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010446
Sebastian Redl623ea822011-05-19 05:13:44 +000010447 // FIXME: If the destructor has a body that could throw, and the newly created
10448 // spec doesn't allow exceptions, we should emit a warning, because this
10449 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010450 // However, we don't have a body or an exception specification yet, so it
10451 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010452}
10453
Pavel Labath58934982013-08-30 08:52:28 +000010454namespace {
10455/// \brief An abstract base class for all helper classes used in building the
10456// copy/move operators. These classes serve as factory functions and help us
10457// avoid using the same Expr* in the AST twice.
10458class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010459 ExprBuilder(const ExprBuilder&) = delete;
10460 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010461
10462protected:
10463 static Expr *assertNotNull(Expr *E) {
10464 assert(E && "Expression construction must not fail.");
10465 return E;
10466 }
10467
10468public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010469 ExprBuilder() {}
10470 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010471
10472 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10473};
10474
10475class RefBuilder: public ExprBuilder {
10476 VarDecl *Var;
10477 QualType VarType;
10478
10479public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010480 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010481 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010482 }
10483
10484 RefBuilder(VarDecl *Var, QualType VarType)
10485 : Var(Var), VarType(VarType) {}
10486};
10487
10488class ThisBuilder: public ExprBuilder {
10489public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010490 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010491 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010492 }
10493};
10494
10495class CastBuilder: public ExprBuilder {
10496 const ExprBuilder &Builder;
10497 QualType Type;
10498 ExprValueKind Kind;
10499 const CXXCastPath &Path;
10500
10501public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010502 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010503 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10504 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010505 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010506 }
10507
10508 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10509 const CXXCastPath &Path)
10510 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10511};
10512
10513class DerefBuilder: public ExprBuilder {
10514 const ExprBuilder &Builder;
10515
10516public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010517 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010518 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010519 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010520 }
10521
10522 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10523};
10524
10525class MemberBuilder: public ExprBuilder {
10526 const ExprBuilder &Builder;
10527 QualType Type;
10528 CXXScopeSpec SS;
10529 bool IsArrow;
10530 LookupResult &MemberLookup;
10531
10532public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010533 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010534 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010535 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010536 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010537 }
10538
10539 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10540 LookupResult &MemberLookup)
10541 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10542 MemberLookup(MemberLookup) {}
10543};
10544
10545class MoveCastBuilder: public ExprBuilder {
10546 const ExprBuilder &Builder;
10547
10548public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010549 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010550 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10551 }
10552
10553 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10554};
10555
10556class LvalueConvBuilder: public ExprBuilder {
10557 const ExprBuilder &Builder;
10558
10559public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010560 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010561 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010562 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010563 }
10564
10565 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10566};
10567
10568class SubscriptBuilder: public ExprBuilder {
10569 const ExprBuilder &Base;
10570 const ExprBuilder &Index;
10571
10572public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010573 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010574 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010575 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010576 }
10577
10578 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10579 : Base(Base), Index(Index) {}
10580};
10581
10582} // end anonymous namespace
10583
Richard Smith41ae3282012-11-14 00:50:40 +000010584/// When generating a defaulted copy or move assignment operator, if a field
10585/// should be copied with __builtin_memcpy rather than via explicit assignments,
10586/// do so. This optimization only applies for arrays of scalars, and for arrays
10587/// of class type where the selected copy/move-assignment operator is trivial.
10588static StmtResult
10589buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010590 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010591 // Compute the size of the memory buffer to be copied.
10592 QualType SizeType = S.Context.getSizeType();
10593 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10594 S.Context.getTypeSizeInChars(T).getQuantity());
10595
10596 // Take the address of the field references for "from" and "to". We
10597 // directly construct UnaryOperators here because semantic analysis
10598 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010599 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010600 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10601 S.Context.getPointerType(From->getType()),
10602 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010603 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010604 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10605 S.Context.getPointerType(To->getType()),
10606 VK_RValue, OK_Ordinary, Loc);
10607
10608 const Type *E = T->getBaseElementTypeUnsafe();
10609 bool NeedsCollectableMemCpy =
10610 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10611
10612 // Create a reference to the __builtin_objc_memmove_collectable function
10613 StringRef MemCpyName = NeedsCollectableMemCpy ?
10614 "__builtin_objc_memmove_collectable" :
10615 "__builtin_memcpy";
10616 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10617 Sema::LookupOrdinaryName);
10618 S.LookupName(R, S.TUScope, true);
10619
10620 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10621 if (!MemCpy)
10622 // Something went horribly wrong earlier, and we will have complained
10623 // about it.
10624 return StmtError();
10625
10626 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010627 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010628 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10629
10630 Expr *CallArgs[] = {
10631 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10632 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010633 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010634 Loc, CallArgs, Loc);
10635
10636 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010637 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010638}
10639
Sebastian Redl22653ba2011-08-30 19:58:05 +000010640/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010641/// \c To.
10642///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010643/// This routine is used to copy/move the members of a class with an
10644/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010645/// copied are arrays, this routine builds for loops to copy them.
10646///
10647/// \param S The Sema object used for type-checking.
10648///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010649/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010650///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010651/// \param T The type of the expressions being copied/moved. Both expressions
10652/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010653///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010654/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010655///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010656/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010657///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010658/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010659/// Otherwise, it's a non-static member subobject.
10660///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010661/// \param Copying Whether we're copying or moving.
10662///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010663/// \param Depth Internal parameter recording the depth of the recursion.
10664///
Richard Smith41ae3282012-11-14 00:50:40 +000010665/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10666/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010667static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010668buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010669 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010670 bool CopyingBaseSubobject, bool Copying,
10671 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010672 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010673 // Each subobject is assigned in the manner appropriate to its type:
10674 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010675 // - if the subobject is of class type, as if by a call to operator= with
10676 // the subobject as the object expression and the corresponding
10677 // subobject of x as a single function argument (as if by explicit
10678 // qualification; that is, ignoring any possible virtual overriding
10679 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010680 //
10681 // C++03 [class.copy]p13:
10682 // - if the subobject is of class type, the copy assignment operator for
10683 // the class is used (as if by explicit qualification; that is,
10684 // ignoring any possible virtual overriding functions in more derived
10685 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010686 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10687 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010688
Douglas Gregorb139cd52010-05-01 20:49:11 +000010689 // Look for operator=.
10690 DeclarationName Name
10691 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10692 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10693 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010694
Richard Smith52c0b582012-11-13 00:54:12 +000010695 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10696 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010697 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010698 LookupResult::Filter F = OpLookup.makeFilter();
10699 while (F.hasNext()) {
10700 NamedDecl *D = F.next();
10701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10702 if (Method->isCopyAssignmentOperator() ||
10703 (!Copying && Method->isMoveAssignmentOperator()))
10704 continue;
10705
10706 F.erase();
10707 }
10708 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010709 }
Richard Smith52c0b582012-11-13 00:54:12 +000010710
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010711 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010712 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010713 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010714 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010715 // ambiguities), we need to cast "this" to that subobject type; to
10716 // ensure that we don't go through the virtual call mechanism, we need
10717 // to qualify the operator= name with the base class (see below). However,
10718 // this means that if the base class has a protected copy assignment
10719 // operator, the protected member access check will fail. So, we
10720 // rewrite "protected" access to "public" access in this case, since we
10721 // know by construction that we're calling from a derived class.
10722 if (CopyingBaseSubobject) {
10723 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10724 L != LEnd; ++L) {
10725 if (L.getAccess() == AS_protected)
10726 L.setAccess(AS_public);
10727 }
10728 }
Richard Smith52c0b582012-11-13 00:54:12 +000010729
Douglas Gregorb139cd52010-05-01 20:49:11 +000010730 // Create the nested-name-specifier that will be used to qualify the
10731 // reference to operator=; this is required to suppress the virtual
10732 // call mechanism.
10733 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000010734 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000010735 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000010736 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000010737 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000010738 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000010739
Douglas Gregorb139cd52010-05-01 20:49:11 +000010740 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000010741 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000010742 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10743 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010744 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000010745 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010746 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010747 /*SuppressQualifierCheck=*/true);
10748 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010749 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010750
Douglas Gregorb139cd52010-05-01 20:49:11 +000010751 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000010752
Pavel Labath58934982013-08-30 08:52:28 +000010753 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000010754 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010755 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000010756 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010757 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010758 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010759
Richard Smith41ae3282012-11-14 00:50:40 +000010760 // If we built a call to a trivial 'operator=' while copying an array,
10761 // bail out. We'll replace the whole shebang with a memcpy.
10762 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10763 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000010764 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010765
Richard Smith52c0b582012-11-13 00:54:12 +000010766 // Convert to an expression-statement, and clean up any produced
10767 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000010768 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010769 }
John McCallab8c2732010-03-16 06:11:48 +000010770
Richard Smith52c0b582012-11-13 00:54:12 +000010771 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000010772 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000010773 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010774 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000010775 ExprResult Assignment = S.CreateBuiltinBinOp(
10776 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010777 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010778 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000010779 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010780 }
Richard Smith52c0b582012-11-13 00:54:12 +000010781
10782 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000010783 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000010784
Douglas Gregorb139cd52010-05-01 20:49:11 +000010785 // Construct a loop over the array bounds, e.g.,
10786 //
10787 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10788 //
10789 // that will copy each of the array elements.
10790 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000010791
Douglas Gregorb139cd52010-05-01 20:49:11 +000010792 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000010793 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010794 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010795 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010796 llvm::raw_svector_ostream OS(Str);
10797 OS << "__i" << Depth;
10798 IterationVarName = &S.Context.Idents.get(OS.str());
10799 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000010800 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010801 IterationVarName, SizeType,
10802 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000010803 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000010804
Douglas Gregorb139cd52010-05-01 20:49:11 +000010805 // Initialize the iteration variable to zero.
10806 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010807 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010808
Pavel Labath58934982013-08-30 08:52:28 +000010809 // Creates a reference to the iteration variable.
10810 RefBuilder IterationVarRef(IterationVar, SizeType);
10811 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000010812
Douglas Gregorb139cd52010-05-01 20:49:11 +000010813 // Create the DeclStmt that holds the iteration variable.
10814 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010815
Douglas Gregorb139cd52010-05-01 20:49:11 +000010816 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000010817 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10818 MoveCastBuilder FromIndexMove(FromIndexCopy);
10819 const ExprBuilder *FromIndex;
10820 if (Copying)
10821 FromIndex = &FromIndexCopy;
10822 else
10823 FromIndex = &FromIndexMove;
10824
10825 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010826
10827 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000010828 StmtResult Copy =
10829 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000010830 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000010831 Copying, Depth + 1);
10832 // Bail out if copying fails or if we determined that we should use memcpy.
10833 if (Copy.isInvalid() || !Copy.get())
10834 return Copy;
10835
10836 // Create the comparison against the array bound.
10837 llvm::APInt Upper
10838 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10839 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000010840 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000010841 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10842 BO_NE, S.Context.BoolTy,
10843 VK_RValue, OK_Ordinary, Loc, false);
10844
10845 // Create the pre-increment of the iteration variable.
10846 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000010847 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10848 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010849
Douglas Gregorb139cd52010-05-01 20:49:11 +000010850 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000010851 return S.ActOnForStmt(
10852 Loc, Loc, InitStmt,
10853 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10854 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010855}
10856
Richard Smith41ae3282012-11-14 00:50:40 +000010857static StmtResult
10858buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010859 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010860 bool CopyingBaseSubobject, bool Copying) {
10861 // Maybe we should use a memcpy?
10862 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10863 T.isTriviallyCopyableType(S.Context))
10864 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10865
10866 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10867 CopyingBaseSubobject,
10868 Copying, 0));
10869
10870 // If we ended up picking a trivial assignment operator for an array of a
10871 // non-trivially-copyable class type, just emit a memcpy.
10872 if (!Result.isInvalid() && !Result.get())
10873 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10874
10875 return Result;
10876}
10877
Richard Smithd3b5c9082012-07-27 04:22:15 +000010878Sema::ImplicitExceptionSpecification
10879Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10880 CXXRecordDecl *ClassDecl = MD->getParent();
10881
10882 ImplicitExceptionSpecification ExceptSpec(*this);
10883 if (ClassDecl->isInvalidDecl())
10884 return ExceptSpec;
10885
10886 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010887 assert(T->getNumParams() == 1 && "not a copy assignment op");
10888 unsigned ArgQuals =
10889 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010890
Douglas Gregor68e11362010-07-01 17:48:08 +000010891 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010892 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010893 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010894
10895 // It is unspecified whether or not an implicit copy assignment operator
10896 // attempts to deduplicate calls to assignment operators of virtual bases are
10897 // made. As such, this exception specification is effectively unspecified.
10898 // Based on a similar decision made for constness in C++0x, we're erring on
10899 // the side of assuming such calls to be made regardless of whether they
10900 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010901 for (const auto &Base : ClassDecl->bases()) {
10902 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010903 continue;
10904
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010905 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010906 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010907 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10908 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010909 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010910 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010911
Aaron Ballman445a9392014-03-13 16:15:17 +000010912 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010913 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010914 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010915 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10916 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010917 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010918 }
10919
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010920 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010921 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010922 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10923 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010924 LookupCopyingAssignment(FieldClassDecl,
10925 ArgQuals | FieldType.getCVRQualifiers(),
10926 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010927 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010928 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010929 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010930
Richard Smithd3b5c9082012-07-27 04:22:15 +000010931 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010932}
10933
10934CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10935 // Note: The following rules are largely analoguous to the copy
10936 // constructor rules. Note that virtual bases are not taken into account
10937 // for determining the argument type of the operator. Note also that
10938 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010939 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010940
Richard Smith8bf22e52012-11-29 01:34:07 +000010941 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10942 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010943 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010944
Alexis Hunt119f3652011-05-14 05:23:20 +000010945 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10946 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010947 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10948 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010949 ArgType = ArgType.withConst();
10950 ArgType = Context.getLValueReferenceType(ArgType);
10951
Richard Smith99005e62013-05-07 03:19:20 +000010952 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10953 CXXCopyAssignment,
10954 Const);
10955
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010956 // An implicitly-declared copy assignment operator is an inline public
10957 // member of its class.
10958 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010959 SourceLocation ClassLoc = ClassDecl->getLocation();
10960 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010961 CXXMethodDecl *CopyAssignment =
10962 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010963 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10964 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010965 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010966 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010967 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010968
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010969 if (getLangOpts().CUDA) {
10970 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10971 CopyAssignment,
10972 /* ConstRHS */ Const,
10973 /* Diagnose */ false);
10974 }
10975
Richard Smithd3b5c9082012-07-27 04:22:15 +000010976 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010977 FunctionProtoType::ExtProtoInfo EPI =
10978 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010979 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010980
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010981 // Add the parameter to the operator.
10982 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010983 ClassLoc, ClassLoc,
10984 /*Id=*/nullptr, ArgType,
10985 /*TInfo=*/nullptr, SC_None,
10986 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010987 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010988
Richard Smith6b02d462012-12-08 08:32:28 +000010989 CopyAssignment->setTrivial(
10990 ClassDecl->needsOverloadResolutionForCopyAssignment()
10991 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10992 : ClassDecl->hasTrivialCopyAssignment());
10993
Richard Smith6b02d462012-12-08 08:32:28 +000010994 // Note that we have added this copy-assignment operator.
10995 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10996
Richard Smith12e79312016-05-13 06:47:56 +000010997 Scope *S = getScopeForContext(ClassDecl);
10998 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10999
11000 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11001 SetDeclDeleted(CopyAssignment, ClassLoc);
11002
11003 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011004 PushOnScopeChains(CopyAssignment, S, false);
11005 ClassDecl->addDecl(CopyAssignment);
11006
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011007 return CopyAssignment;
11008}
11009
Richard Smithd577fbb2013-06-13 03:23:42 +000011010/// Diagnose an implicit copy operation for a class which is odr-used, but
11011/// which is deprecated because the class has a user-declared copy constructor,
11012/// copy assignment operator, or destructor.
11013static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11014 SourceLocation UseLoc) {
11015 assert(CopyOp->isImplicit());
11016
11017 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011018 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011019
11020 // In Microsoft mode, assignment operations don't affect constructors and
11021 // vice versa.
11022 if (RD->hasUserDeclaredDestructor()) {
11023 UserDeclaredOperation = RD->getDestructor();
11024 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11025 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011026 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011027 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011028 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011029 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011030 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011031 break;
11032 }
11033 }
11034 assert(UserDeclaredOperation);
11035 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11036 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011037 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011038 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011039 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011040 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011041 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011042 break;
11043 }
11044 }
11045 assert(UserDeclaredOperation);
11046 }
11047
11048 if (UserDeclaredOperation) {
11049 S.Diag(UserDeclaredOperation->getLocation(),
11050 diag::warn_deprecated_copy_operation)
11051 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11052 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11053 S.Diag(UseLoc, diag::note_member_synthesized_at)
11054 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11055 : Sema::CXXCopyAssignment)
11056 << RD;
11057 }
11058}
11059
Douglas Gregorb139cd52010-05-01 20:49:11 +000011060void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11061 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011062 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011063 CopyAssignOperator->isOverloadedOperator() &&
11064 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011065 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11066 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011067 "DefineImplicitCopyAssignment called for wrong function");
11068
11069 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11070
11071 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11072 CopyAssignOperator->setInvalidDecl();
11073 return;
11074 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011075
11076 // C++11 [class.copy]p18:
11077 // The [definition of an implicitly declared copy assignment operator] is
11078 // deprecated if the class has a user-declared copy constructor or a
11079 // user-declared destructor.
11080 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11081 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11082
Eli Friedman276dd182013-09-05 00:02:25 +000011083 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011084
Eli Friedmaneaf34142012-10-18 20:14:08 +000011085 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011086 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011087
11088 // C++0x [class.copy]p30:
11089 // The implicitly-defined or explicitly-defaulted copy assignment operator
11090 // for a non-union class X performs memberwise copy assignment of its
11091 // subobjects. The direct base classes of X are assigned first, in the
11092 // order of their declaration in the base-specifier-list, and then the
11093 // immediate non-static data members of X are assigned, in the order in
11094 // which they were declared in the class definition.
11095
11096 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011097 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011098
11099 // The parameter for the "other" object, which we are copying from.
11100 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11101 Qualifiers OtherQuals = Other->getType().getQualifiers();
11102 QualType OtherRefType = Other->getType();
11103 if (const LValueReferenceType *OtherRef
11104 = OtherRefType->getAs<LValueReferenceType>()) {
11105 OtherRefType = OtherRef->getPointeeType();
11106 OtherQuals = OtherRefType.getQualifiers();
11107 }
11108
11109 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011110 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11111 ? CopyAssignOperator->getLocEnd()
11112 : CopyAssignOperator->getLocation();
11113
Pavel Labath58934982013-08-30 08:52:28 +000011114 // Builds a DeclRefExpr for the "other" object.
11115 RefBuilder OtherRef(Other, OtherRefType);
11116
11117 // Builds the "this" pointer.
11118 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011119
11120 // Assign base classes.
11121 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011122 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011123 // Form the assignment:
11124 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011125 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011126 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011127 Invalid = true;
11128 continue;
11129 }
11130
John McCallcf142162010-08-07 06:22:56 +000011131 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011132 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011133
Douglas Gregorb139cd52010-05-01 20:49:11 +000011134 // Construct the "from" expression, which is an implicit cast to the
11135 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011136 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11137 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011138
11139 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011140 DerefBuilder DerefThis(This);
11141 CastBuilder To(DerefThis,
11142 Context.getCVRQualifiedType(
11143 BaseType, CopyAssignOperator->getTypeQualifiers()),
11144 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011145
11146 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011147 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011148 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011149 /*CopyingBaseSubobject=*/true,
11150 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011151 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011152 Diag(CurrentLocation, diag::note_member_synthesized_at)
11153 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11154 CopyAssignOperator->setInvalidDecl();
11155 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011156 }
11157
11158 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011159 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011160 }
11161
Douglas Gregorb139cd52010-05-01 20:49:11 +000011162 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011163 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011164 // FIXME: We should form some kind of AST representation for the implied
11165 // memcpy in a union copy operation.
11166 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011167 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011168
11169 if (Field->isInvalidDecl()) {
11170 Invalid = true;
11171 continue;
11172 }
11173
Douglas Gregorb139cd52010-05-01 20:49:11 +000011174 // Check for members of reference type; we can't copy those.
11175 if (Field->getType()->isReferenceType()) {
11176 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11177 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11178 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011179 Diag(CurrentLocation, diag::note_member_synthesized_at)
11180 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011181 Invalid = true;
11182 continue;
11183 }
11184
11185 // Check for members of const-qualified, non-class type.
11186 QualType BaseType = Context.getBaseElementType(Field->getType());
11187 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11188 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11189 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11190 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011191 Diag(CurrentLocation, diag::note_member_synthesized_at)
11192 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011193 Invalid = true;
11194 continue;
11195 }
John McCall1b1a1db2011-06-17 00:18:42 +000011196
11197 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011198 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11199 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011200
11201 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011202 if (FieldType->isIncompleteArrayType()) {
11203 assert(ClassDecl->hasFlexibleArrayMember() &&
11204 "Incomplete array type is not valid");
11205 continue;
11206 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011207
11208 // Build references to the field in the object we're copying from and to.
11209 CXXScopeSpec SS; // Intentionally empty
11210 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11211 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011212 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011213 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011214
11215 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11216
11217 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011218
Douglas Gregorb139cd52010-05-01 20:49:11 +000011219 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011220 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011221 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011222 /*CopyingBaseSubobject=*/false,
11223 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011224 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011225 Diag(CurrentLocation, diag::note_member_synthesized_at)
11226 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11227 CopyAssignOperator->setInvalidDecl();
11228 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011229 }
11230
11231 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011232 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011233 }
11234
11235 if (!Invalid) {
11236 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011237 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011238
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011239 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011240 if (Return.isInvalid())
11241 Invalid = true;
11242 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011243 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011244
11245 if (Trap.hasErrorOccurred()) {
11246 Diag(CurrentLocation, diag::note_member_synthesized_at)
11247 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11248 Invalid = true;
11249 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011250 }
11251 }
11252
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011253 // The exception specification is needed because we are defining the
11254 // function.
11255 ResolveExceptionSpec(CurrentLocation,
11256 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11257
Douglas Gregorb139cd52010-05-01 20:49:11 +000011258 if (Invalid) {
11259 CopyAssignOperator->setInvalidDecl();
11260 return;
11261 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011262
11263 StmtResult Body;
11264 {
11265 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011266 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011267 /*isStmtExpr=*/false);
11268 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11269 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011270 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011271
11272 if (ASTMutationListener *L = getASTMutationListener()) {
11273 L->CompletedImplicitDefinition(CopyAssignOperator);
11274 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011275}
11276
Sebastian Redl22653ba2011-08-30 19:58:05 +000011277Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011278Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11279 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011280
Richard Smithd3b5c9082012-07-27 04:22:15 +000011281 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011282 if (ClassDecl->isInvalidDecl())
11283 return ExceptSpec;
11284
11285 // C++0x [except.spec]p14:
11286 // An implicitly declared special member function (Clause 12) shall have an
11287 // exception-specification. [...]
11288
11289 // It is unspecified whether or not an implicit move assignment operator
11290 // attempts to deduplicate calls to assignment operators of virtual bases are
11291 // made. As such, this exception specification is effectively unspecified.
11292 // Based on a similar decision made for constness in C++0x, we're erring on
11293 // the side of assuming such calls to be made regardless of whether they
11294 // actually happen.
11295 // Note that a move constructor is not implicitly declared when there are
11296 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000011297 for (const auto &Base : ClassDecl->bases()) {
11298 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000011299 continue;
11300
11301 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011302 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011303 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011304 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011305 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011306 }
11307
Aaron Ballman445a9392014-03-13 16:15:17 +000011308 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011309 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011310 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011311 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011312 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011313 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011314 }
11315
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011316 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011317 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011318 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011319 if (CXXMethodDecl *MoveAssign =
11320 LookupMovingAssignment(FieldClassDecl,
11321 FieldType.getCVRQualifiers(),
11322 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011323 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011324 }
11325 }
11326
11327 return ExceptSpec;
11328}
11329
11330CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011331 assert(ClassDecl->needsImplicitMoveAssignment());
11332
Richard Smith8bf22e52012-11-29 01:34:07 +000011333 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11334 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011335 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011336
Sebastian Redl22653ba2011-08-30 19:58:05 +000011337 // Note: The following rules are largely analoguous to the move
11338 // constructor rules.
11339
Sebastian Redl22653ba2011-08-30 19:58:05 +000011340 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11341 QualType RetType = Context.getLValueReferenceType(ArgType);
11342 ArgType = Context.getRValueReferenceType(ArgType);
11343
Richard Smith99005e62013-05-07 03:19:20 +000011344 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11345 CXXMoveAssignment,
11346 false);
11347
Sebastian Redl22653ba2011-08-30 19:58:05 +000011348 // An implicitly-declared move assignment operator is an inline public
11349 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011350 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11351 SourceLocation ClassLoc = ClassDecl->getLocation();
11352 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011353 CXXMethodDecl *MoveAssignment =
11354 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011355 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011356 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011357 MoveAssignment->setAccess(AS_public);
11358 MoveAssignment->setDefaulted();
11359 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011360
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011361 if (getLangOpts().CUDA) {
11362 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11363 MoveAssignment,
11364 /* ConstRHS */ false,
11365 /* Diagnose */ false);
11366 }
11367
Richard Smithd3b5c9082012-07-27 04:22:15 +000011368 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011369 FunctionProtoType::ExtProtoInfo EPI =
11370 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011371 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011372
Sebastian Redl22653ba2011-08-30 19:58:05 +000011373 // Add the parameter to the operator.
11374 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011375 ClassLoc, ClassLoc,
11376 /*Id=*/nullptr, ArgType,
11377 /*TInfo=*/nullptr, SC_None,
11378 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011379 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011380
Richard Smith6b02d462012-12-08 08:32:28 +000011381 MoveAssignment->setTrivial(
11382 ClassDecl->needsOverloadResolutionForMoveAssignment()
11383 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11384 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011385
Richard Smith12e79312016-05-13 06:47:56 +000011386 // Note that we have added this copy-assignment operator.
11387 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11388
11389 Scope *S = getScopeForContext(ClassDecl);
11390 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11391
Richard Smithd951a1d2012-02-18 02:02:13 +000011392 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011393 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11394 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011395 }
11396
Richard Smith12e79312016-05-13 06:47:56 +000011397 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011398 PushOnScopeChains(MoveAssignment, S, false);
11399 ClassDecl->addDecl(MoveAssignment);
11400
Sebastian Redl22653ba2011-08-30 19:58:05 +000011401 return MoveAssignment;
11402}
11403
Richard Smithb2504bd2013-11-04 04:26:14 +000011404/// Check if we're implicitly defining a move assignment operator for a class
11405/// with virtual bases. Such a move assignment might move-assign the virtual
11406/// base multiple times.
11407static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11408 SourceLocation CurrentLocation) {
11409 assert(!Class->isDependentContext() && "should not define dependent move");
11410
11411 // Only a virtual base could get implicitly move-assigned multiple times.
11412 // Only a non-trivial move assignment can observe this. We only want to
11413 // diagnose if we implicitly define an assignment operator that assigns
11414 // two base classes, both of which move-assign the same virtual base.
11415 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11416 Class->getNumBases() < 2)
11417 return;
11418
11419 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11420 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11421 VBaseMap VBases;
11422
Aaron Ballman574705e2014-03-13 15:41:46 +000011423 for (auto &BI : Class->bases()) {
11424 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011425 while (!Worklist.empty()) {
11426 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11427 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11428
11429 // If the base has no non-trivial move assignment operators,
11430 // we don't care about moves from it.
11431 if (!Base->hasNonTrivialMoveAssignment())
11432 continue;
11433
11434 // If there's nothing virtual here, skip it.
11435 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11436 continue;
11437
11438 // If we're not actually going to call a move assignment for this base,
11439 // or the selected move assignment is trivial, skip it.
11440 Sema::SpecialMemberOverloadResult *SMOR =
11441 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11442 /*ConstArg*/false, /*VolatileArg*/false,
11443 /*RValueThis*/true, /*ConstThis*/false,
11444 /*VolatileThis*/false);
11445 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11446 !SMOR->getMethod()->isMoveAssignmentOperator())
11447 continue;
11448
11449 if (BaseSpec->isVirtual()) {
11450 // We're going to move-assign this virtual base, and its move
11451 // assignment operator is not trivial. If this can happen for
11452 // multiple distinct direct bases of Class, diagnose it. (If it
11453 // only happens in one base, we'll diagnose it when synthesizing
11454 // that base class's move assignment operator.)
11455 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011456 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011457 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011458 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011459 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11460 << Class << Base;
11461 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11462 << (Base->getCanonicalDecl() ==
11463 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11464 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011465 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011466 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011467 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11468 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011469
11470 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011471 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011472 }
11473 } else {
11474 // Only walk over bases that have defaulted move assignment operators.
11475 // We assume that any user-provided move assignment operator handles
11476 // the multiple-moves-of-vbase case itself somehow.
11477 if (!SMOR->getMethod()->isDefaulted())
11478 continue;
11479
11480 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011481 for (auto &BI : Base->bases())
11482 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011483 }
11484 }
11485 }
11486}
11487
Sebastian Redl22653ba2011-08-30 19:58:05 +000011488void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11489 CXXMethodDecl *MoveAssignOperator) {
11490 assert((MoveAssignOperator->isDefaulted() &&
11491 MoveAssignOperator->isOverloadedOperator() &&
11492 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011493 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11494 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011495 "DefineImplicitMoveAssignment called for wrong function");
11496
11497 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11498
11499 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11500 MoveAssignOperator->setInvalidDecl();
11501 return;
11502 }
11503
Eli Friedman276dd182013-09-05 00:02:25 +000011504 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011505
Eli Friedmaneaf34142012-10-18 20:14:08 +000011506 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011507 DiagnosticErrorTrap Trap(Diags);
11508
11509 // C++0x [class.copy]p28:
11510 // The implicitly-defined or move assignment operator for a non-union class
11511 // X performs memberwise move assignment of its subobjects. The direct base
11512 // classes of X are assigned first, in the order of their declaration in the
11513 // base-specifier-list, and then the immediate non-static data members of X
11514 // are assigned, in the order in which they were declared in the class
11515 // definition.
11516
Richard Smithb2504bd2013-11-04 04:26:14 +000011517 // Issue a warning if our implicit move assignment operator will move
11518 // from a virtual base more than once.
11519 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011520
Sebastian Redl22653ba2011-08-30 19:58:05 +000011521 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011522 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011523
11524 // The parameter for the "other" object, which we are move from.
11525 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11526 QualType OtherRefType = Other->getType()->
11527 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011528 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011529 "Bad argument type of defaulted move assignment");
11530
11531 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011532 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11533 ? MoveAssignOperator->getLocEnd()
11534 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011535
Pavel Labath58934982013-08-30 08:52:28 +000011536 // Builds a reference to the "other" object.
11537 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011538 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011539 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011540
Pavel Labath58934982013-08-30 08:52:28 +000011541 // Builds the "this" pointer.
11542 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011543
Sebastian Redl22653ba2011-08-30 19:58:05 +000011544 // Assign base classes.
11545 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011546 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011547 // C++11 [class.copy]p28:
11548 // It is unspecified whether subobjects representing virtual base classes
11549 // are assigned more than once by the implicitly-defined copy assignment
11550 // operator.
11551 // FIXME: Do not assign to a vbase that will be assigned by some other base
11552 // class. For a move-assignment, this can result in the vbase being moved
11553 // multiple times.
11554
Sebastian Redl22653ba2011-08-30 19:58:05 +000011555 // Form the assignment:
11556 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011557 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011558 if (!BaseType->isRecordType()) {
11559 Invalid = true;
11560 continue;
11561 }
11562
11563 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011564 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011565
11566 // Construct the "from" expression, which is an implicit cast to the
11567 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011568 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011569
11570 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011571 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011572
11573 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011574 CastBuilder To(DerefThis,
11575 Context.getCVRQualifiedType(
11576 BaseType, MoveAssignOperator->getTypeQualifiers()),
11577 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011578
11579 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011580 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011581 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011582 /*CopyingBaseSubobject=*/true,
11583 /*Copying=*/false);
11584 if (Move.isInvalid()) {
11585 Diag(CurrentLocation, diag::note_member_synthesized_at)
11586 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11587 MoveAssignOperator->setInvalidDecl();
11588 return;
11589 }
11590
11591 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011592 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011593 }
11594
Sebastian Redl22653ba2011-08-30 19:58:05 +000011595 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011596 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011597 // FIXME: We should form some kind of AST representation for the implied
11598 // memcpy in a union copy operation.
11599 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011600 continue;
11601
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011602 if (Field->isInvalidDecl()) {
11603 Invalid = true;
11604 continue;
11605 }
11606
Sebastian Redl22653ba2011-08-30 19:58:05 +000011607 // Check for members of reference type; we can't move those.
11608 if (Field->getType()->isReferenceType()) {
11609 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11610 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11611 Diag(Field->getLocation(), diag::note_declared_at);
11612 Diag(CurrentLocation, diag::note_member_synthesized_at)
11613 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11614 Invalid = true;
11615 continue;
11616 }
11617
11618 // Check for members of const-qualified, non-class type.
11619 QualType BaseType = Context.getBaseElementType(Field->getType());
11620 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11621 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11622 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11623 Diag(Field->getLocation(), diag::note_declared_at);
11624 Diag(CurrentLocation, diag::note_member_synthesized_at)
11625 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11626 Invalid = true;
11627 continue;
11628 }
11629
11630 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011631 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11632 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011633
11634 QualType FieldType = Field->getType().getNonReferenceType();
11635 if (FieldType->isIncompleteArrayType()) {
11636 assert(ClassDecl->hasFlexibleArrayMember() &&
11637 "Incomplete array type is not valid");
11638 continue;
11639 }
11640
11641 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011642 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11643 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011644 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011645 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011646 MemberBuilder From(MoveOther, OtherRefType,
11647 /*IsArrow=*/false, MemberLookup);
11648 MemberBuilder To(This, getCurrentThisType(),
11649 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011650
Pavel Labath58934982013-08-30 08:52:28 +000011651 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011652 "Member reference with rvalue base must be rvalue except for reference "
11653 "members, which aren't allowed for move assignment.");
11654
Sebastian Redl22653ba2011-08-30 19:58:05 +000011655 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011656 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011657 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011658 /*CopyingBaseSubobject=*/false,
11659 /*Copying=*/false);
11660 if (Move.isInvalid()) {
11661 Diag(CurrentLocation, diag::note_member_synthesized_at)
11662 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11663 MoveAssignOperator->setInvalidDecl();
11664 return;
11665 }
Richard Smith11d19592012-11-12 23:33:00 +000011666
Sebastian Redl22653ba2011-08-30 19:58:05 +000011667 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011668 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011669 }
11670
11671 if (!Invalid) {
11672 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011673 ExprResult ThisObj =
11674 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11675
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011676 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011677 if (Return.isInvalid())
11678 Invalid = true;
11679 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011680 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011681
11682 if (Trap.hasErrorOccurred()) {
11683 Diag(CurrentLocation, diag::note_member_synthesized_at)
11684 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11685 Invalid = true;
11686 }
11687 }
11688 }
11689
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011690 // The exception specification is needed because we are defining the
11691 // function.
11692 ResolveExceptionSpec(CurrentLocation,
11693 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11694
Sebastian Redl22653ba2011-08-30 19:58:05 +000011695 if (Invalid) {
11696 MoveAssignOperator->setInvalidDecl();
11697 return;
11698 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011699
11700 StmtResult Body;
11701 {
11702 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011703 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011704 /*isStmtExpr=*/false);
11705 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11706 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011707 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011708
11709 if (ASTMutationListener *L = getASTMutationListener()) {
11710 L->CompletedImplicitDefinition(MoveAssignOperator);
11711 }
11712}
11713
Richard Smithd3b5c9082012-07-27 04:22:15 +000011714Sema::ImplicitExceptionSpecification
11715Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11716 CXXRecordDecl *ClassDecl = MD->getParent();
11717
11718 ImplicitExceptionSpecification ExceptSpec(*this);
11719 if (ClassDecl->isInvalidDecl())
11720 return ExceptSpec;
11721
11722 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011723 assert(T->getNumParams() >= 1 && "not a copy ctor");
11724 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011725
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011726 // C++ [except.spec]p14:
11727 // An implicitly declared special member function (Clause 12) shall have an
11728 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000011729 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011730 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000011731 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011732 continue;
11733
Douglas Gregora6d69502010-07-02 23:41:54 +000011734 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011735 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011736 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011737 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000011738 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011739 }
Aaron Ballman445a9392014-03-13 16:15:17 +000011740 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000011741 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011742 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011743 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011744 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000011745 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011746 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011747 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011748 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000011749 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11750 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000011751 LookupCopyingConstructor(FieldClassDecl,
11752 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000011753 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011754 }
11755 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011756
Richard Smithd3b5c9082012-07-27 04:22:15 +000011757 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000011758}
11759
11760CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11761 CXXRecordDecl *ClassDecl) {
11762 // C++ [class.copy]p4:
11763 // If the class definition does not explicitly declare a copy
11764 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011765 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011766
Richard Smith8bf22e52012-11-29 01:34:07 +000011767 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11768 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011769 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011770
Alexis Hunt913820d2011-05-13 06:10:58 +000011771 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11772 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011773 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011774 if (Const)
11775 ArgType = ArgType.withConst();
11776 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011777
Richard Smithb5800092012-06-10 05:43:50 +000011778 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11779 CXXCopyConstructor,
11780 Const);
11781
Douglas Gregor54be3392010-07-01 17:57:27 +000011782 DeclarationName Name
11783 = Context.DeclarationNames.getCXXConstructorName(
11784 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011785 SourceLocation ClassLoc = ClassDecl->getLocation();
11786 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011787
11788 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011789 // member of its class.
11790 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011791 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011792 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011793 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011794 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011795 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011796
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011797 if (getLangOpts().CUDA) {
11798 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11799 CopyConstructor,
11800 /* ConstRHS */ Const,
11801 /* Diagnose */ false);
11802 }
11803
Richard Smithd3b5c9082012-07-27 04:22:15 +000011804 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011805 FunctionProtoType::ExtProtoInfo EPI =
11806 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011807 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011808 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011809
Douglas Gregor54be3392010-07-01 17:57:27 +000011810 // Add the parameter to the constructor.
11811 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011812 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011813 /*IdentifierInfo=*/nullptr,
11814 ArgType, /*TInfo=*/nullptr,
11815 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011816 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011817
Richard Smith6b02d462012-12-08 08:32:28 +000011818 CopyConstructor->setTrivial(
11819 ClassDecl->needsOverloadResolutionForCopyConstructor()
11820 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11821 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011822
Richard Smith6b02d462012-12-08 08:32:28 +000011823 // Note that we have declared this constructor.
11824 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11825
Richard Smith12e79312016-05-13 06:47:56 +000011826 Scope *S = getScopeForContext(ClassDecl);
11827 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11828
11829 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11830 SetDeclDeleted(CopyConstructor, ClassLoc);
11831
11832 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011833 PushOnScopeChains(CopyConstructor, S, false);
11834 ClassDecl->addDecl(CopyConstructor);
11835
Douglas Gregor54be3392010-07-01 17:57:27 +000011836 return CopyConstructor;
11837}
11838
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011839void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011840 CXXConstructorDecl *CopyConstructor) {
11841 assert((CopyConstructor->isDefaulted() &&
11842 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011843 !CopyConstructor->doesThisDeclarationHaveABody() &&
11844 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011845 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011846
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011847 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011848 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011849
Richard Smithd577fbb2013-06-13 03:23:42 +000011850 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011851 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011852 // deprecated if the class has a user-declared copy assignment operator
11853 // or a user-declared destructor.
11854 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11855 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11856
Eli Friedmaneaf34142012-10-18 20:14:08 +000011857 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011858 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011859
David Blaikie3fc2f912013-01-17 05:26:25 +000011860 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011861 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011862 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011863 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011864 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011865 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011866 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11867 ? CopyConstructor->getLocEnd()
11868 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011869 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011870 CopyConstructor->setBody(
11871 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011872 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011873
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011874 // The exception specification is needed because we are defining the
11875 // function.
11876 ResolveExceptionSpec(CurrentLocation,
11877 CopyConstructor->getType()->castAs<FunctionProtoType>());
11878
Eli Friedman276dd182013-09-05 00:02:25 +000011879 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011880 MarkVTableUsed(CurrentLocation, ClassDecl);
11881
Sebastian Redlab238a72011-04-24 16:28:06 +000011882 if (ASTMutationListener *L = getASTMutationListener()) {
11883 L->CompletedImplicitDefinition(CopyConstructor);
11884 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011885}
11886
Sebastian Redl22653ba2011-08-30 19:58:05 +000011887Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011888Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11889 CXXRecordDecl *ClassDecl = MD->getParent();
11890
Sebastian Redl22653ba2011-08-30 19:58:05 +000011891 // C++ [except.spec]p14:
11892 // An implicitly declared special member function (Clause 12) shall have an
11893 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011894 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011895 if (ClassDecl->isInvalidDecl())
11896 return ExceptSpec;
11897
11898 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011899 for (const auto &B : ClassDecl->bases()) {
11900 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011901 continue;
11902
Aaron Ballman574705e2014-03-13 15:41:46 +000011903 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011904 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011905 CXXConstructorDecl *Constructor =
11906 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011907 // If this is a deleted function, add it anyway. This might be conformant
11908 // with the standard. This might not. I'm not sure. It might not matter.
11909 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011910 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011911 }
11912 }
11913
11914 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011915 for (const auto &B : ClassDecl->vbases()) {
11916 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011917 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011918 CXXConstructorDecl *Constructor =
11919 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011920 // If this is a deleted function, add it anyway. This might be conformant
11921 // with the standard. This might not. I'm not sure. It might not matter.
11922 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011923 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011924 }
11925 }
11926
11927 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011928 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011929 QualType FieldType = Context.getBaseElementType(F->getType());
11930 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11931 CXXConstructorDecl *Constructor =
11932 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011933 // If this is a deleted function, add it anyway. This might be conformant
11934 // with the standard. This might not. I'm not sure. It might not matter.
11935 // In particular, the problem is that this function never gets called. It
11936 // might just be ill-formed because this function attempts to refer to
11937 // a deleted function here.
11938 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011939 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011940 }
11941 }
11942
11943 return ExceptSpec;
11944}
11945
11946CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11947 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011948 assert(ClassDecl->needsImplicitMoveConstructor());
11949
Richard Smith8bf22e52012-11-29 01:34:07 +000011950 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11951 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011952 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011953
Sebastian Redl22653ba2011-08-30 19:58:05 +000011954 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11955 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011956
Richard Smithb5800092012-06-10 05:43:50 +000011957 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11958 CXXMoveConstructor,
11959 false);
11960
Sebastian Redl22653ba2011-08-30 19:58:05 +000011961 DeclarationName Name
11962 = Context.DeclarationNames.getCXXConstructorName(
11963 Context.getCanonicalType(ClassType));
11964 SourceLocation ClassLoc = ClassDecl->getLocation();
11965 DeclarationNameInfo NameInfo(Name, ClassLoc);
11966
Richard Smith99005e62013-05-07 03:19:20 +000011967 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011968 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011969 // member of its class.
11970 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011971 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011972 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011973 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011974 MoveConstructor->setAccess(AS_public);
11975 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011976
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011977 if (getLangOpts().CUDA) {
11978 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11979 MoveConstructor,
11980 /* ConstRHS */ false,
11981 /* Diagnose */ false);
11982 }
11983
Richard Smithd3b5c9082012-07-27 04:22:15 +000011984 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011985 FunctionProtoType::ExtProtoInfo EPI =
11986 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011987 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011988 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011989
Sebastian Redl22653ba2011-08-30 19:58:05 +000011990 // Add the parameter to the constructor.
11991 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11992 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011993 /*IdentifierInfo=*/nullptr,
11994 ArgType, /*TInfo=*/nullptr,
11995 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011996 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011997
Richard Smith6b02d462012-12-08 08:32:28 +000011998 MoveConstructor->setTrivial(
11999 ClassDecl->needsOverloadResolutionForMoveConstructor()
12000 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12001 : ClassDecl->hasTrivialMoveConstructor());
12002
Richard Smith12e79312016-05-13 06:47:56 +000012003 // Note that we have declared this constructor.
12004 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12005
12006 Scope *S = getScopeForContext(ClassDecl);
12007 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12008
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012009 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012010 ClassDecl->setImplicitMoveConstructorIsDeleted();
12011 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012012 }
12013
Richard Smith12e79312016-05-13 06:47:56 +000012014 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012015 PushOnScopeChains(MoveConstructor, S, false);
12016 ClassDecl->addDecl(MoveConstructor);
12017
12018 return MoveConstructor;
12019}
12020
12021void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12022 CXXConstructorDecl *MoveConstructor) {
12023 assert((MoveConstructor->isDefaulted() &&
12024 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012025 !MoveConstructor->doesThisDeclarationHaveABody() &&
12026 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012027 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12028
12029 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12030 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12031
Eli Friedmaneaf34142012-10-18 20:14:08 +000012032 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012033 DiagnosticErrorTrap Trap(Diags);
12034
David Blaikie3fc2f912013-01-17 05:26:25 +000012035 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012036 Trap.hasErrorOccurred()) {
12037 Diag(CurrentLocation, diag::note_member_synthesized_at)
12038 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12039 MoveConstructor->setInvalidDecl();
12040 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012041 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12042 ? MoveConstructor->getLocEnd()
12043 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012044 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012045 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012046 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012047 }
12048
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012049 // The exception specification is needed because we are defining the
12050 // function.
12051 ResolveExceptionSpec(CurrentLocation,
12052 MoveConstructor->getType()->castAs<FunctionProtoType>());
12053
Eli Friedman276dd182013-09-05 00:02:25 +000012054 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012055 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012056
12057 if (ASTMutationListener *L = getASTMutationListener()) {
12058 L->CompletedImplicitDefinition(MoveConstructor);
12059 }
12060}
12061
Douglas Gregor74f7d502012-02-15 19:33:52 +000012062bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012063 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012064}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012065
12066void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012067 SourceLocation CurrentLocation,
12068 CXXConversionDecl *Conv) {
12069 CXXRecordDecl *Lambda = Conv->getParent();
12070 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12071 // If we are defining a specialization of a conversion to function-ptr
12072 // cache the deduced template arguments for this specialization
12073 // so that we can use them to retrieve the corresponding call-operator
12074 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012075 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12076
Faisal Vali571df122013-09-29 08:45:24 +000012077 // Retrieve the corresponding call-operator specialization.
12078 if (Lambda->isGenericLambda()) {
12079 assert(Conv->isFunctionTemplateSpecialization());
12080 FunctionTemplateDecl *CallOpTemplate =
12081 CallOp->getDescribedFunctionTemplate();
12082 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012083 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012084 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012085 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012086 InsertPos);
12087 assert(CallOpSpec &&
12088 "Conversion operator must have a corresponding call operator");
12089 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12090 }
12091 // Mark the call operator referenced (and add to pending instantiations
12092 // if necessary).
12093 // For both the conversion and static-invoker template specializations
12094 // we construct their body's in this function, so no need to add them
12095 // to the PendingInstantiations.
12096 MarkFunctionReferenced(CurrentLocation, CallOp);
12097
Eli Friedmaneaf34142012-10-18 20:14:08 +000012098 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012099 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012100
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012101 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012102 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12103 // ... and get the corresponding specialization for a generic lambda.
12104 if (Lambda->isGenericLambda()) {
12105 assert(DeducedTemplateArgs &&
12106 "Must have deduced template arguments from Conversion Operator");
12107 FunctionTemplateDecl *InvokeTemplate =
12108 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012109 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012110 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012111 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012112 InsertPos);
12113 assert(InvokeSpec &&
12114 "Must have a corresponding static invoker specialization");
12115 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12116 }
12117 // Construct the body of the conversion function { return __invoke; }.
12118 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012119 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012120 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012121 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012122 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12123 Conv->getLocation(),
12124 Conv->getLocation()));
12125
12126 Conv->markUsed(Context);
12127 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012128
Faisal Vali571df122013-09-29 08:45:24 +000012129 // Fill in the __invoke function with a dummy implementation. IR generation
12130 // will fill in the actual details.
12131 Invoker->markUsed(Context);
12132 Invoker->setReferenced();
12133 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12134
Douglas Gregord3b672c2012-02-16 01:06:16 +000012135 if (ASTMutationListener *L = getASTMutationListener()) {
12136 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012137 L->CompletedImplicitDefinition(Invoker);
12138 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012139}
12140
Faisal Vali571df122013-09-29 08:45:24 +000012141
12142
Douglas Gregord3b672c2012-02-16 01:06:16 +000012143void Sema::DefineImplicitLambdaToBlockPointerConversion(
12144 SourceLocation CurrentLocation,
12145 CXXConversionDecl *Conv)
12146{
Faisal Vali850da1a2013-09-29 17:08:32 +000012147 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012148
Eli Friedman276dd182013-09-05 00:02:25 +000012149 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012150
Eli Friedmaneaf34142012-10-18 20:14:08 +000012151 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012152 DiagnosticErrorTrap Trap(Diags);
12153
Douglas Gregored90df32012-02-22 05:02:47 +000012154 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012155 Expr *This = ActOnCXXThis(CurrentLocation).get();
12156 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012157
Eli Friedman98b01ed2012-03-01 04:01:32 +000012158 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12159 Conv->getLocation(),
12160 Conv, DerefThis);
12161
12162 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12163 // behavior. Note that only the general conversion function does this
12164 // (since it's unusable otherwise); in the case where we inline the
12165 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012166 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012167 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12168 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012169 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012170
12171 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012172 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012173 Conv->setInvalidDecl();
12174 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012175 }
Douglas Gregored90df32012-02-22 05:02:47 +000012176
Douglas Gregored90df32012-02-22 05:02:47 +000012177 // Create the return statement that returns the block from the conversion
12178 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012179 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012180 if (Return.isInvalid()) {
12181 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12182 Conv->setInvalidDecl();
12183 return;
12184 }
12185
12186 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012187 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012188 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012189 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012190 Conv->getLocation()));
12191
Douglas Gregored90df32012-02-22 05:02:47 +000012192 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012193 if (ASTMutationListener *L = getASTMutationListener()) {
12194 L->CompletedImplicitDefinition(Conv);
12195 }
12196}
12197
Douglas Gregord2f70072012-03-10 06:53:13 +000012198/// \brief Determine whether the given list arguments contains exactly one
12199/// "real" (non-default) argument.
12200static bool hasOneRealArgument(MultiExprArg Args) {
12201 switch (Args.size()) {
12202 case 0:
12203 return false;
12204
12205 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012206 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012207 return false;
12208
12209 // fall through
12210 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012211 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012212 }
12213
12214 return false;
12215}
12216
John McCalldadc5752010-08-24 06:29:42 +000012217ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012218Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012219 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012220 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012221 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012222 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012223 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012224 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012225 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012226 unsigned ConstructKind,
12227 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012228 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012229
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012230 // C++0x [class.copy]p34:
12231 // When certain criteria are met, an implementation is allowed to
12232 // omit the copy/move construction of a class object, even if the
12233 // copy/move constructor and/or destructor for the object have
12234 // side effects. [...]
12235 // - when a temporary class object that has not been bound to a
12236 // reference (12.2) would be copied/moved to a class object
12237 // with the same cv-unqualified type, the copy/move operation
12238 // can be omitted by constructing the temporary object
12239 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012240 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012241 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012242 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012243 Elidable = SubExpr->isTemporaryObject(
12244 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012245 }
Mike Stump11289f42009-09-09 15:08:12 +000012246
Richard Smithc2bebe92016-05-11 20:37:46 +000012247 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12248 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012249 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012250 IsListInitialization,
12251 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012252 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012253}
12254
John McCalldadc5752010-08-24 06:29:42 +000012255ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012256Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012257 NamedDecl *FoundDecl,
12258 CXXConstructorDecl *Constructor,
12259 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012260 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012261 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012262 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012263 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012264 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012265 unsigned ConstructKind,
12266 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012267 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012268 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012269 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12270 return ExprError();
12271 }
Richard Smith5179eb72016-06-28 19:03:57 +000012272
Richard Smithc83bf822016-06-10 00:58:19 +000012273 return BuildCXXConstructExpr(
12274 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12275 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12276 RequiresZeroInit, ConstructKind, ParenRange);
12277}
12278
12279/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12280/// including handling of its default argument expressions.
12281ExprResult
12282Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12283 CXXConstructorDecl *Constructor,
12284 bool Elidable,
12285 MultiExprArg ExprArgs,
12286 bool HadMultipleCandidates,
12287 bool IsListInitialization,
12288 bool IsStdInitListInitialization,
12289 bool RequiresZeroInit,
12290 unsigned ConstructKind,
12291 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012292 assert(declaresSameEntity(
12293 Constructor->getParent(),
12294 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12295 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012296 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012297 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12298 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012299
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012300 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012301 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012302 ExprArgs, HadMultipleCandidates, IsListInitialization,
12303 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012304 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12305 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012306}
12307
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012308ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12309 assert(Field->hasInClassInitializer());
12310
12311 // If we already have the in-class initializer nothing needs to be done.
12312 if (Field->getInClassInitializer())
12313 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12314
12315 // Maybe we haven't instantiated the in-class initializer. Go check the
12316 // pattern FieldDecl to see if it has one.
12317 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12318
12319 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12320 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12321 DeclContext::lookup_result Lookup =
12322 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012323
12324 // Lookup can return at most two results: the pattern for the field, or the
12325 // injected class name of the parent record. No other member can have the
12326 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012327 // In modules mode, lookup can return multiple results (coming from
12328 // different modules).
12329 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012330 "more than two lookup results for field name");
12331 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12332 if (!Pattern) {
12333 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12334 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012335 for (auto L : Lookup)
12336 if (isa<FieldDecl>(L)) {
12337 Pattern = cast<FieldDecl>(L);
12338 break;
12339 }
12340 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012341 }
12342
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012343 if (InstantiateInClassInitializer(Loc, Field, Pattern,
12344 getTemplateInstantiationArgs(Field)))
12345 return ExprError();
12346 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12347 }
12348
12349 // DR1351:
12350 // If the brace-or-equal-initializer of a non-static data member
12351 // invokes a defaulted default constructor of its class or of an
12352 // enclosing class in a potentially evaluated subexpression, the
12353 // program is ill-formed.
12354 //
12355 // This resolution is unworkable: the exception specification of the
12356 // default constructor can be needed in an unevaluated context, in
12357 // particular, in the operand of a noexcept-expression, and we can be
12358 // unable to compute an exception specification for an enclosed class.
12359 //
12360 // Any attempt to resolve the exception specification of a defaulted default
12361 // constructor before the initializer is lexically complete will ultimately
12362 // come here at which point we can diagnose it.
12363 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12364 if (OutermostClass == ParentRD) {
12365 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12366 << ParentRD << Field;
12367 } else {
12368 Diag(Field->getLocEnd(),
12369 diag::err_in_class_initializer_not_yet_parsed_outer_class)
12370 << ParentRD << OutermostClass << Field;
12371 }
12372
12373 return ExprError();
12374}
12375
John McCall03c48482010-02-02 09:10:11 +000012376void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012377 if (VD->isInvalidDecl()) return;
12378
John McCall03c48482010-02-02 09:10:11 +000012379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012380 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012381 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012382 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012383
Chandler Carruth86d17d32011-03-27 21:26:48 +000012384 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012385 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012386 CheckDestructorAccess(VD->getLocation(), Destructor,
12387 PDiag(diag::err_access_dtor_var)
12388 << VD->getDeclName()
12389 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012390 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012391
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012392 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012393 if (!VD->hasGlobalStorage()) return;
12394
12395 // Emit warning for non-trivial dtor in global scope (a real global,
12396 // class-static, function-static).
12397 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12398
12399 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012400 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012401 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012402}
12403
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012404/// \brief Given a constructor and the set of arguments provided for the
12405/// constructor, convert the arguments and add any required default arguments
12406/// to form a proper call to this constructor.
12407///
12408/// \returns true if an error occurred, false otherwise.
12409bool
12410Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12411 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012412 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012413 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012414 bool AllowExplicit,
12415 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012416 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12417 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012418 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012419
12420 const FunctionProtoType *Proto
12421 = Constructor->getType()->getAs<FunctionProtoType>();
12422 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012423 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012424
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012425 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012426 if (NumArgs < NumParams)
12427 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012428 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012429 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012430
12431 VariadicCallType CallType =
12432 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012433 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012434 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012435 Proto, 0,
12436 llvm::makeArrayRef(Args, NumArgs),
12437 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012438 CallType, AllowExplicit,
12439 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012440 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012441
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012442 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012443
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012444 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012445 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012446 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012447
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012448 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012449}
12450
Anders Carlssone363c8e2009-12-12 00:32:00 +000012451static inline bool
12452CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12453 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012454 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012455 if (isa<NamespaceDecl>(DC)) {
12456 return SemaRef.Diag(FnDecl->getLocation(),
12457 diag::err_operator_new_delete_declared_in_namespace)
12458 << FnDecl->getDeclName();
12459 }
12460
12461 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012462 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012463 return SemaRef.Diag(FnDecl->getLocation(),
12464 diag::err_operator_new_delete_declared_static)
12465 << FnDecl->getDeclName();
12466 }
12467
Anders Carlsson60659a82009-12-12 02:43:16 +000012468 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012469}
12470
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012471static inline bool
12472CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12473 CanQualType ExpectedResultType,
12474 CanQualType ExpectedFirstParamType,
12475 unsigned DependentParamTypeDiag,
12476 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012477 QualType ResultType =
12478 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012479
12480 // Check that the result type is not dependent.
12481 if (ResultType->isDependentType())
12482 return SemaRef.Diag(FnDecl->getLocation(),
12483 diag::err_operator_new_delete_dependent_result_type)
12484 << FnDecl->getDeclName() << ExpectedResultType;
12485
12486 // Check that the result type is what we expect.
12487 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12488 return SemaRef.Diag(FnDecl->getLocation(),
12489 diag::err_operator_new_delete_invalid_result_type)
12490 << FnDecl->getDeclName() << ExpectedResultType;
12491
12492 // A function template must have at least 2 parameters.
12493 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12494 return SemaRef.Diag(FnDecl->getLocation(),
12495 diag::err_operator_new_delete_template_too_few_parameters)
12496 << FnDecl->getDeclName();
12497
12498 // The function decl must have at least 1 parameter.
12499 if (FnDecl->getNumParams() == 0)
12500 return SemaRef.Diag(FnDecl->getLocation(),
12501 diag::err_operator_new_delete_too_few_parameters)
12502 << FnDecl->getDeclName();
12503
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012504 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012505 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12506 if (FirstParamType->isDependentType())
12507 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12508 << FnDecl->getDeclName() << ExpectedFirstParamType;
12509
12510 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012511 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012512 ExpectedFirstParamType)
12513 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12514 << FnDecl->getDeclName() << ExpectedFirstParamType;
12515
12516 return false;
12517}
12518
Anders Carlsson12308f42009-12-11 23:23:22 +000012519static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012520CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012521 // C++ [basic.stc.dynamic.allocation]p1:
12522 // A program is ill-formed if an allocation function is declared in a
12523 // namespace scope other than global scope or declared static in global
12524 // scope.
12525 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12526 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012527
12528 CanQualType SizeTy =
12529 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12530
12531 // C++ [basic.stc.dynamic.allocation]p1:
12532 // The return type shall be void*. The first parameter shall have type
12533 // std::size_t.
12534 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12535 SizeTy,
12536 diag::err_operator_new_dependent_param_type,
12537 diag::err_operator_new_param_type))
12538 return true;
12539
12540 // C++ [basic.stc.dynamic.allocation]p1:
12541 // The first parameter shall not have an associated default argument.
12542 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012543 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012544 diag::err_operator_new_default_arg)
12545 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12546
12547 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012548}
12549
12550static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012551CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012552 // C++ [basic.stc.dynamic.deallocation]p1:
12553 // A program is ill-formed if deallocation functions are declared in a
12554 // namespace scope other than global scope or declared static in global
12555 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012556 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12557 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012558
12559 // C++ [basic.stc.dynamic.deallocation]p2:
12560 // Each deallocation function shall return void and its first parameter
12561 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012562 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12563 SemaRef.Context.VoidPtrTy,
12564 diag::err_operator_delete_dependent_param_type,
12565 diag::err_operator_delete_param_type))
12566 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012567
Anders Carlsson12308f42009-12-11 23:23:22 +000012568 return false;
12569}
12570
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012571/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12572/// of this overloaded operator is well-formed. If so, returns false;
12573/// otherwise, emits appropriate diagnostics and returns true.
12574bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012575 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012576 "Expected an overloaded operator declaration");
12577
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012578 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12579
Mike Stump11289f42009-09-09 15:08:12 +000012580 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012581 // The allocation and deallocation functions, operator new,
12582 // operator new[], operator delete and operator delete[], are
12583 // described completely in 3.7.3. The attributes and restrictions
12584 // found in the rest of this subclause do not apply to them unless
12585 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012586 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012587 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012588
Anders Carlsson22f443f2009-12-12 00:26:23 +000012589 if (Op == OO_New || Op == OO_Array_New)
12590 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012591
12592 // C++ [over.oper]p6:
12593 // An operator function shall either be a non-static member
12594 // function or be a non-member function and have at least one
12595 // parameter whose type is a class, a reference to a class, an
12596 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012597 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12598 if (MethodDecl->isStatic())
12599 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012600 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012601 } else {
12602 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012603 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012604 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012605 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12606 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012607 ClassOrEnumParam = true;
12608 break;
12609 }
12610 }
12611
Douglas Gregord69246b2008-11-17 16:14:12 +000012612 if (!ClassOrEnumParam)
12613 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012614 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012615 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012616 }
12617
12618 // C++ [over.oper]p8:
12619 // An operator function cannot have default arguments (8.3.6),
12620 // except where explicitly stated below.
12621 //
Mike Stump11289f42009-09-09 15:08:12 +000012622 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012623 // (C++ [over.call]p1).
12624 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012625 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012626 if (Param->hasDefaultArg())
12627 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012628 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012629 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012630 }
12631 }
12632
Douglas Gregor6cf08062008-11-10 13:38:07 +000012633 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12634 { false, false, false }
12635#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12636 , { Unary, Binary, MemberOnly }
12637#include "clang/Basic/OperatorKinds.def"
12638 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012639
Douglas Gregor6cf08062008-11-10 13:38:07 +000012640 bool CanBeUnaryOperator = OperatorUses[Op][0];
12641 bool CanBeBinaryOperator = OperatorUses[Op][1];
12642 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012643
12644 // C++ [over.oper]p8:
12645 // [...] Operator functions cannot have more or fewer parameters
12646 // than the number required for the corresponding operator, as
12647 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012648 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012649 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012650 if (Op != OO_Call &&
12651 ((NumParams == 1 && !CanBeUnaryOperator) ||
12652 (NumParams == 2 && !CanBeBinaryOperator) ||
12653 (NumParams < 1) || (NumParams > 2))) {
12654 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012655 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012656 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012657 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012658 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012659 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012660 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012661 assert(CanBeBinaryOperator &&
12662 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012663 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012664 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012665
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012666 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012667 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012668 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012669
Douglas Gregord69246b2008-11-17 16:14:12 +000012670 // Overloaded operators other than operator() cannot be variadic.
12671 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012672 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012673 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012674 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012675 }
12676
12677 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012678 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12679 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012680 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012681 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012682 }
12683
12684 // C++ [over.inc]p1:
12685 // The user-defined function called operator++ implements the
12686 // prefix and postfix ++ operator. If this function is a member
12687 // function with no parameters, or a non-member function with one
12688 // parameter of class or enumeration type, it defines the prefix
12689 // increment operator ++ for objects of that type. If the function
12690 // is a member function with one parameter (which shall be of type
12691 // int) or a non-member function with two parameters (the second
12692 // of which shall be of type int), it defines the postfix
12693 // increment operator ++ for objects of that type.
12694 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12695 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012696 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012697
Richard Smith538b52a2014-01-30 22:24:05 +000012698 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12699 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012700 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012701 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012702 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012703 }
12704
Douglas Gregord69246b2008-11-17 16:14:12 +000012705 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012706}
Chris Lattner3b024a32008-12-17 07:09:26 +000012707
Richard Smithc28aee62016-02-17 00:04:04 +000012708static bool
12709checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12710 FunctionTemplateDecl *TpDecl) {
12711 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12712
12713 // Must have one or two template parameters.
12714 if (TemplateParams->size() == 1) {
12715 NonTypeTemplateParmDecl *PmDecl =
12716 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12717
12718 // The template parameter must be a char parameter pack.
12719 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12720 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12721 return false;
12722
12723 } else if (TemplateParams->size() == 2) {
12724 TemplateTypeParmDecl *PmType =
12725 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12726 NonTypeTemplateParmDecl *PmArgs =
12727 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12728
12729 // The second template parameter must be a parameter pack with the
12730 // first template parameter as its type.
12731 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12732 PmArgs->isTemplateParameterPack()) {
12733 const TemplateTypeParmType *TArgs =
12734 PmArgs->getType()->getAs<TemplateTypeParmType>();
12735 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12736 TArgs->getIndex() == PmType->getIndex()) {
12737 if (SemaRef.ActiveTemplateInstantiations.empty())
12738 SemaRef.Diag(TpDecl->getLocation(),
12739 diag::ext_string_literal_operator_template);
12740 return false;
12741 }
12742 }
12743 }
12744
12745 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12746 diag::err_literal_operator_template)
12747 << TpDecl->getTemplateParameters()->getSourceRange();
12748 return true;
12749}
12750
Alexis Huntc88db062010-01-13 09:01:02 +000012751/// CheckLiteralOperatorDeclaration - Check whether the declaration
12752/// of this literal operator function is well-formed. If so, returns
12753/// false; otherwise, emits appropriate diagnostics and returns true.
12754bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012755 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012756 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12757 << FnDecl->getDeclName();
12758 return true;
12759 }
12760
Richard Smith72eebee2012-03-04 09:41:16 +000012761 if (FnDecl->isExternC()) {
12762 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012763 if (const LinkageSpecDecl *LSD =
12764 FnDecl->getDeclContext()->getExternCContext())
12765 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012766 return true;
12767 }
12768
Richard Smithbcc22fc2012-03-09 08:00:36 +000012769 // This might be the definition of a literal operator template.
12770 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012771
Richard Smithbcc22fc2012-03-09 08:00:36 +000012772 // This might be a specialization of a literal operator template.
12773 if (!TpDecl)
12774 TpDecl = FnDecl->getPrimaryTemplate();
12775
Richard Smithb8b41d32013-10-07 19:57:58 +000012776 // template <char...> type operator "" name() and
12777 // template <class T, T...> type operator "" name() are the only valid
12778 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012779 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012780 if (FnDecl->param_size() != 0) {
12781 Diag(FnDecl->getLocation(),
12782 diag::err_literal_operator_template_with_params);
12783 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012784 }
Richard Smithc28aee62016-02-17 00:04:04 +000012785
12786 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12787 return true;
12788
12789 } else if (FnDecl->param_size() == 1) {
12790 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12791
12792 QualType ParamType = Param->getType().getUnqualifiedType();
12793
12794 // Only unsigned long long int, long double, any character type, and const
12795 // char * are allowed as the only parameters.
12796 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12797 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12798 Context.hasSameType(ParamType, Context.CharTy) ||
12799 Context.hasSameType(ParamType, Context.WideCharTy) ||
12800 Context.hasSameType(ParamType, Context.Char16Ty) ||
12801 Context.hasSameType(ParamType, Context.Char32Ty)) {
12802 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12803 QualType InnerType = Ptr->getPointeeType();
12804
12805 // Pointer parameter must be a const char *.
12806 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12807 Context.CharTy) &&
12808 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12809 Diag(Param->getSourceRange().getBegin(),
12810 diag::err_literal_operator_param)
12811 << ParamType << "'const char *'" << Param->getSourceRange();
12812 return true;
12813 }
12814
12815 } else if (ParamType->isRealFloatingType()) {
12816 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12817 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12818 return true;
12819
12820 } else if (ParamType->isIntegerType()) {
12821 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12822 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12823 return true;
12824
12825 } else {
12826 Diag(Param->getSourceRange().getBegin(),
12827 diag::err_literal_operator_invalid_param)
12828 << ParamType << Param->getSourceRange();
12829 return true;
12830 }
12831
12832 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012833 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12834
Richard Smithc28aee62016-02-17 00:04:04 +000012835 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012836
Richard Smithc28aee62016-02-17 00:04:04 +000012837 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12838
12839 // Two parameter function must have a pointer to const as a
12840 // first parameter; let's strip those qualifiers.
12841 const PointerType *PT = FirstParamType->getAs<PointerType>();
12842
12843 if (!PT) {
12844 Diag((*Param)->getSourceRange().getBegin(),
12845 diag::err_literal_operator_param)
12846 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12847 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012848 }
12849
Richard Smithc28aee62016-02-17 00:04:04 +000012850 QualType PointeeType = PT->getPointeeType();
12851 // First parameter must be const
12852 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12853 Diag((*Param)->getSourceRange().getBegin(),
12854 diag::err_literal_operator_param)
12855 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12856 return true;
12857 }
Alexis Huntc88db062010-01-13 09:01:02 +000012858
Richard Smithc28aee62016-02-17 00:04:04 +000012859 QualType InnerType = PointeeType.getUnqualifiedType();
12860 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12861 // are allowed as the first parameter to a two-parameter function
12862 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12863 Context.hasSameType(InnerType, Context.WideCharTy) ||
12864 Context.hasSameType(InnerType, Context.Char16Ty) ||
12865 Context.hasSameType(InnerType, Context.Char32Ty))) {
12866 Diag((*Param)->getSourceRange().getBegin(),
12867 diag::err_literal_operator_param)
12868 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12869 return true;
12870 }
12871
12872 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012873 ++Param;
12874
Richard Smithc28aee62016-02-17 00:04:04 +000012875 // The second parameter must be a std::size_t.
12876 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12877 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12878 Diag((*Param)->getSourceRange().getBegin(),
12879 diag::err_literal_operator_param)
12880 << SecondParamType << Context.getSizeType()
12881 << (*Param)->getSourceRange();
12882 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012883 }
Richard Smithc28aee62016-02-17 00:04:04 +000012884 } else {
12885 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012886 return true;
12887 }
12888
Richard Smithc28aee62016-02-17 00:04:04 +000012889 // Parameters are good.
12890
Richard Smith768cecc2012-03-09 08:16:22 +000012891 // A parameter-declaration-clause containing a default argument is not
12892 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012893 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012894 if (Param->hasDefaultArg()) {
12895 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012896 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012897 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012898 break;
12899 }
12900 }
12901
Richard Smith0df56f42012-03-08 02:39:21 +000012902 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012903 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12904 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012905 // C++11 [usrlit.suffix]p1:
12906 // Literal suffix identifiers that do not start with an underscore
12907 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012908 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12909 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012910 }
Richard Smith0df56f42012-03-08 02:39:21 +000012911
Alexis Huntc88db062010-01-13 09:01:02 +000012912 return false;
12913}
12914
Douglas Gregor07665a62009-01-05 19:45:36 +000012915/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12916/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012917/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12918/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012919/// the '{' brace. Otherwise, this linkage specification does not
12920/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012921Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012922 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012923 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012924 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12925 if (!Lit->isAscii()) {
12926 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12927 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012928 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012929 }
12930
12931 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012932 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012933 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012934 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012935 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012936 Language = LinkageSpecDecl::lang_cxx;
12937 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012938 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12939 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012940 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012941 }
Mike Stump11289f42009-09-09 15:08:12 +000012942
Chris Lattner438e5012008-12-17 07:13:27 +000012943 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000012944
Richard Smith4ee696d2014-02-17 23:25:27 +000012945 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12946 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000012947 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012948 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000012949 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000012950 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000012951}
12952
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000012953/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000012954/// the C++ linkage specification LinkageSpec. If RBraceLoc is
12955/// valid, it's the position of the closing '}' brace in a linkage
12956/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000012957Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012958 Decl *LinkageSpec,
12959 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012960 if (RBraceLoc.isValid()) {
12961 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12962 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012963 }
Richard Smith4ee696d2014-02-17 23:25:27 +000012964 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000012965 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000012966}
12967
Michael Han84324352013-02-22 17:15:32 +000012968Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12969 AttributeList *AttrList,
12970 SourceLocation SemiLoc) {
12971 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12972 // Attribute declarations appertain to empty declaration so we handle
12973 // them here.
12974 if (AttrList)
12975 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000012976
Michael Han84324352013-02-22 17:15:32 +000012977 CurContext->addDecl(ED);
12978 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000012979}
12980
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012981/// \brief Perform semantic analysis for the variable declaration that
12982/// occurs within a C++ catch clause, returning the newly-created
12983/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012984VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000012985 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012986 SourceLocation StartLoc,
12987 SourceLocation Loc,
12988 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012989 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012990 QualType ExDeclType = TInfo->getType();
12991
Sebastian Redl54c04d42008-12-22 19:15:10 +000012992 // Arrays and functions decay.
12993 if (ExDeclType->isArrayType())
12994 ExDeclType = Context.getArrayDecayedType(ExDeclType);
12995 else if (ExDeclType->isFunctionType())
12996 ExDeclType = Context.getPointerType(ExDeclType);
12997
12998 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12999 // The exception-declaration shall not denote a pointer or reference to an
13000 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013001 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013002 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013003 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013004 Invalid = true;
13005 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013006
David Majnemere56d1a02016-06-08 16:05:07 +000013007 if (ExDeclType->isVariablyModifiedType()) {
13008 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13009 Invalid = true;
13010 }
13011
Sebastian Redl54c04d42008-12-22 19:15:10 +000013012 QualType BaseType = ExDeclType;
13013 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013014 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013015 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013016 BaseType = Ptr->getPointeeType();
13017 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013018 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013019 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013020 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013021 BaseType = Ref->getPointeeType();
13022 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013023 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013024 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013025 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013026 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013027 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013028
Mike Stump11289f42009-09-09 15:08:12 +000013029 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013030 RequireNonAbstractType(Loc, ExDeclType,
13031 diag::err_abstract_type_in_decl,
13032 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013033 Invalid = true;
13034
John McCall2ca705e2010-07-24 00:37:23 +000013035 // Only the non-fragile NeXT runtime currently supports C++ catches
13036 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013037 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013038 QualType T = ExDeclType;
13039 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13040 T = RT->getPointeeType();
13041
13042 if (T->isObjCObjectType()) {
13043 Diag(Loc, diag::err_objc_object_catch);
13044 Invalid = true;
13045 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013046 // FIXME: should this be a test for macosx-fragile specifically?
13047 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013048 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013049 }
13050 }
13051
Abramo Bagnaradff19302011-03-08 08:55:46 +000013052 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013053 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013054 ExDecl->setExceptionVariable(true);
13055
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013056 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013057 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013058 Invalid = true;
13059
Douglas Gregor750734c2011-07-06 18:14:43 +000013060 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013061 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013062 // Insulate this from anything else we might currently be parsing.
13063 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13064
Douglas Gregor6de584c2010-03-05 23:38:39 +000013065 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013066 // The object declared in an exception-declaration or, if the
13067 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013068 // copy-initialized (8.5) from the exception object. [...]
13069 // The object is destroyed when the handler exits, after the destruction
13070 // of any automatic objects initialized within the handler.
13071 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013072 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013073 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013074 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013075
13076 InitializedEntity entity =
13077 InitializedEntity::InitializeVariable(ExDecl);
13078 InitializationKind initKind =
13079 InitializationKind::CreateCopy(Loc, SourceLocation());
13080
13081 Expr *opaqueValue =
13082 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013083 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13084 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013085 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013086 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013087 else {
13088 // If the constructor used was non-trivial, set this as the
13089 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013090 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013091 if (!construct->getConstructor()->isTrivial()) {
13092 Expr *init = MaybeCreateExprWithCleanups(construct);
13093 ExDecl->setInit(init);
13094 }
13095
13096 // And make sure it's destructable.
13097 FinalizeVarWithDestructor(ExDecl, recordType);
13098 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013099 }
13100 }
13101
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013102 if (Invalid)
13103 ExDecl->setInvalidDecl();
13104
13105 return ExDecl;
13106}
13107
13108/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13109/// handler.
John McCall48871652010-08-21 09:40:31 +000013110Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013111 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013112 bool Invalid = D.isInvalidType();
13113
13114 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013115 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13116 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013117 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13118 D.getIdentifierLoc());
13119 Invalid = true;
13120 }
13121
Sebastian Redl54c04d42008-12-22 19:15:10 +000013122 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013123 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013124 LookupOrdinaryName,
13125 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013126 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013127 // it contains any previous declaration, except for function parameters in
13128 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013129 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013130 if (isDeclInScope(PrevDecl, CurContext, S)) {
13131 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13132 << D.getIdentifier();
13133 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13134 Invalid = true;
13135 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013136 // Maybe we will complain about the shadowed template parameter.
13137 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013138 }
13139
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013140 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013141 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13142 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013143 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013144 }
13145
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013146 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013147 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013148 D.getIdentifierLoc(),
13149 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013150 if (Invalid)
13151 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013152
Sebastian Redl54c04d42008-12-22 19:15:10 +000013153 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013154 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013155 PushOnScopeChains(ExDecl, S);
13156 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013157 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013158
Douglas Gregor758a8692009-06-17 21:51:59 +000013159 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013160 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013161}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013162
Abramo Bagnaraea947882011-03-08 16:41:52 +000013163Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013164 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013165 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013166 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013167 StringLiteral *AssertMessage =
13168 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013169
Richard Smithded9c2e2012-07-11 22:37:56 +000013170 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013171 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013172
13173 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13174 AssertMessage, RParenLoc, false);
13175}
13176
13177Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13178 Expr *AssertExpr,
13179 StringLiteral *AssertMessage,
13180 SourceLocation RParenLoc,
13181 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013182 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013183 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13184 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013185 // In a static_assert-declaration, the constant-expression shall be a
13186 // constant expression that can be contextually converted to bool.
13187 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13188 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013189 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013190
Richard Smith902ca212011-12-14 23:32:26 +000013191 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013192 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013193 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013194 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013195 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013196
Richard Smithded9c2e2012-07-11 22:37:56 +000013197 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013198 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013199 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013200 if (AssertMessage)
13201 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013202 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013203 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013204 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013205 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013206 }
Mike Stump11289f42009-09-09 15:08:12 +000013207
Abramo Bagnaraea947882011-03-08 16:41:52 +000013208 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013209 AssertExpr, AssertMessage, RParenLoc,
13210 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013211
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013212 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013213 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013214}
Sebastian Redlf769df52009-03-24 22:27:57 +000013215
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013216/// \brief Perform semantic analysis of the given friend type declaration.
13217///
13218/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013219FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013220 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013221 TypeSourceInfo *TSInfo) {
13222 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13223
13224 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013225 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013226
Richard Smithc8239732011-10-18 21:39:00 +000013227 // C++03 [class.friend]p2:
13228 // An elaborated-type-specifier shall be used in a friend declaration
13229 // for a class.*
13230 //
13231 // * The class-key of the elaborated-type-specifier is required.
13232 if (!ActiveTemplateInstantiations.empty()) {
13233 // Do not complain about the form of friend template types during
13234 // template instantiation; we will already have complained when the
13235 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000013236 } else {
13237 if (!T->isElaboratedTypeSpecifier()) {
13238 // If we evaluated the type to a record type, suggest putting
13239 // a tag in front.
13240 if (const RecordType *RT = T->getAs<RecordType>()) {
13241 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013242
13243 SmallString<16> InsertionText(" ");
13244 InsertionText += RD->getKindName();
13245
Nick Lewycky36722d22013-02-06 05:59:33 +000013246 Diag(TypeRange.getBegin(),
13247 getLangOpts().CPlusPlus11 ?
13248 diag::warn_cxx98_compat_unelaborated_friend_type :
13249 diag::ext_unelaborated_friend_type)
13250 << (unsigned) RD->getTagKind()
13251 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013252 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013253 InsertionText);
13254 } else {
13255 Diag(FriendLoc,
13256 getLangOpts().CPlusPlus11 ?
13257 diag::warn_cxx98_compat_nonclass_type_friend :
13258 diag::ext_nonclass_type_friend)
13259 << T
13260 << TypeRange;
13261 }
13262 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013263 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013264 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013265 diag::warn_cxx98_compat_enum_friend :
13266 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013267 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013268 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013269 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013270
Nick Lewycky36722d22013-02-06 05:59:33 +000013271 // C++11 [class.friend]p3:
13272 // A friend declaration that does not declare a function shall have one
13273 // of the following forms:
13274 // friend elaborated-type-specifier ;
13275 // friend simple-type-specifier ;
13276 // friend typename-specifier ;
13277 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13278 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13279 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013280
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013281 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013282 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013283 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013284 return FriendDecl::Create(Context, CurContext,
13285 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13286 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013287}
13288
John McCallace48cd2010-10-19 01:40:49 +000013289/// Handle a friend tag declaration where the scope specifier was
13290/// templated.
13291Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13292 unsigned TagSpec, SourceLocation TagLoc,
13293 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013294 IdentifierInfo *Name,
13295 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013296 AttributeList *Attr,
13297 MultiTemplateParamsArg TempParamLists) {
13298 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13299
13300 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013301 bool Invalid = false;
13302
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013303 if (TemplateParameterList *TemplateParams =
13304 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013305 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013306 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013307 if (TemplateParams->size() > 0) {
13308 // This is a declaration of a class template.
13309 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013310 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013311
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013312 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13313 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013314 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013315 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013316 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013317 } else {
13318 // The "template<>" header is extraneous.
13319 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13320 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13321 isExplicitSpecialization = true;
13322 }
13323 }
13324
Craig Topperc3ec1492014-05-26 06:22:03 +000013325 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013326
John McCallace48cd2010-10-19 01:40:49 +000013327 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013328 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013329 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013330 isAllExplicitSpecializations = false;
13331 break;
13332 }
13333 }
13334
13335 // FIXME: don't ignore attributes.
13336
13337 // If it's explicit specializations all the way down, just forget
13338 // about the template header and build an appropriate non-templated
13339 // friend. TODO: for source fidelity, remember the headers.
13340 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013341 if (SS.isEmpty()) {
13342 bool Owned = false;
13343 bool IsDependent = false;
13344 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013345 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013346 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013347 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013348 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013349 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013350 /*UnderlyingType=*/TypeResult(),
13351 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013352 }
Richard Smith649c7b062014-01-08 00:56:48 +000013353
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013354 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013355 ElaboratedTypeKeyword Keyword
13356 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013357 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013358 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013359 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013360 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013361
13362 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13363 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013364 DependentNameTypeLoc TL =
13365 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013366 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013367 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013368 TL.setNameLoc(NameLoc);
13369 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013370 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013371 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013372 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013373 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013374 }
13375
13376 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013377 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013378 Friend->setAccess(AS_public);
13379 CurContext->addDecl(Friend);
13380 return Friend;
13381 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013382
13383 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13384
13385
John McCallace48cd2010-10-19 01:40:49 +000013386
13387 // Handle the case of a templated-scope friend class. e.g.
13388 // template <class T> class A<T>::B;
13389 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013390 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13391 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013392 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13393 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13394 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013395 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013396 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013397 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013398 TL.setNameLoc(NameLoc);
13399
13400 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013401 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013402 Friend->setAccess(AS_public);
13403 Friend->setUnsupportedFriend(true);
13404 CurContext->addDecl(Friend);
13405 return Friend;
13406}
13407
13408
John McCall11083da2009-09-16 22:47:08 +000013409/// Handle a friend type declaration. This works in tandem with
13410/// ActOnTag.
13411///
13412/// Notes on friend class templates:
13413///
13414/// We generally treat friend class declarations as if they were
13415/// declaring a class. So, for example, the elaborated type specifier
13416/// in a friend declaration is required to obey the restrictions of a
13417/// class-head (i.e. no typedefs in the scope chain), template
13418/// parameters are required to match up with simple template-ids, &c.
13419/// However, unlike when declaring a template specialization, it's
13420/// okay to refer to a template specialization without an empty
13421/// template parameter declaration, e.g.
13422/// friend class A<T>::B<unsigned>;
13423/// We permit this as a special case; if there are any template
13424/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013425/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013426Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013427 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013428 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013429
13430 assert(DS.isFriendSpecified());
13431 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13432
John McCall11083da2009-09-16 22:47:08 +000013433 // Try to convert the decl specifier to a type. This works for
13434 // friend templates because ActOnTag never produces a ClassTemplateDecl
13435 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013436 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013437 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13438 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013439 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013440 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013441
Douglas Gregor6c110f32010-12-16 01:14:37 +000013442 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013443 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013444
John McCall11083da2009-09-16 22:47:08 +000013445 // This is definitely an error in C++98. It's probably meant to
13446 // be forbidden in C++0x, too, but the specification is just
13447 // poorly written.
13448 //
13449 // The problem is with declarations like the following:
13450 // template <T> friend A<T>::foo;
13451 // where deciding whether a class C is a friend or not now hinges
13452 // on whether there exists an instantiation of A that causes
13453 // 'foo' to equal C. There are restrictions on class-heads
13454 // (which we declare (by fiat) elaborated friend declarations to
13455 // be) that makes this tractable.
13456 //
13457 // FIXME: handle "template <> friend class A<T>;", which
13458 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013459 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013460 Diag(Loc, diag::err_tagless_friend_type_template)
13461 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013462 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013463 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013464
John McCallaa74a0c2009-08-28 07:59:38 +000013465 // C++98 [class.friend]p1: A friend of a class is a function
13466 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013467 // This is fixed in DR77, which just barely didn't make the C++03
13468 // deadline. It's also a very silly restriction that seriously
13469 // affects inner classes and which nobody else seems to implement;
13470 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013471 //
13472 // But note that we could warn about it: it's always useless to
13473 // friend one of your own members (it's not, however, worthless to
13474 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013475
John McCall11083da2009-09-16 22:47:08 +000013476 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013477 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013478 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013479 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013480 TSI,
John McCall11083da2009-09-16 22:47:08 +000013481 DS.getFriendSpecLoc());
13482 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013483 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013484
13485 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013486 return nullptr;
13487
John McCall11083da2009-09-16 22:47:08 +000013488 D->setAccess(AS_public);
13489 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013490
John McCall48871652010-08-21 09:40:31 +000013491 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013492}
13493
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013494NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13495 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013496 const DeclSpec &DS = D.getDeclSpec();
13497
13498 assert(DS.isFriendSpecified());
13499 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13500
13501 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013502 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013503
13504 // C++ [class.friend]p1
13505 // A friend of a class is a function or class....
13506 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013507 // It *doesn't* see through dependent types, which is correct
13508 // according to [temp.arg.type]p3:
13509 // If a declaration acquires a function type through a
13510 // type dependent on a template-parameter and this causes
13511 // a declaration that does not use the syntactic form of a
13512 // function declarator to have a function type, the program
13513 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013514 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013515 Diag(Loc, diag::err_unexpected_friend);
13516
13517 // It might be worthwhile to try to recover by creating an
13518 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013519 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013520 }
13521
13522 // C++ [namespace.memdef]p3
13523 // - If a friend declaration in a non-local class first declares a
13524 // class or function, the friend class or function is a member
13525 // of the innermost enclosing namespace.
13526 // - The name of the friend is not found by simple name lookup
13527 // until a matching declaration is provided in that namespace
13528 // scope (either before or after the class declaration granting
13529 // friendship).
13530 // - If a friend function is called, its name may be found by the
13531 // name lookup that considers functions from namespaces and
13532 // classes associated with the types of the function arguments.
13533 // - When looking for a prior declaration of a class or a function
13534 // declared as a friend, scopes outside the innermost enclosing
13535 // namespace scope are not considered.
13536
John McCallde3fd222010-10-12 23:13:28 +000013537 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013538 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13539 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013540 assert(Name);
13541
Douglas Gregor6c110f32010-12-16 01:14:37 +000013542 // Check for unexpanded parameter packs.
13543 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13544 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13545 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013546 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013547
John McCall07e91c02009-08-06 02:15:43 +000013548 // The context we found the declaration in, or in which we should
13549 // create the declaration.
13550 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013551 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013552 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013553 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013554
Richard Smith114394f2013-08-09 04:35:01 +000013555 // There are five cases here.
13556 // - There's no scope specifier and we're in a local class. Only look
13557 // for functions declared in the immediately-enclosing block scope.
13558 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013559 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013560 if ((SS.isInvalid() || !SS.isSet()) &&
13561 (FunctionContainingLocalClass =
13562 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13563 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013564 // If a friend declaration appears in a local class and the name
13565 // specified is an unqualified name, a prior declaration is
13566 // looked up without considering scopes that are outside the
13567 // innermost enclosing non-class scope. For a friend function
13568 // declaration, if there is no prior declaration, the program is
13569 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013570
13571 // Find the innermost enclosing non-class scope. This is the block
13572 // scope containing the local class definition (or for a nested class,
13573 // the outer local class).
13574 DCScope = S->getFnParent();
13575
13576 // Look up the function name in the scope.
13577 Previous.clear(LookupLocalFriendName);
13578 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13579
13580 if (!Previous.empty()) {
13581 // All possible previous declarations must have the same context:
13582 // either they were declared at block scope or they are members of
13583 // one of the enclosing local classes.
13584 DC = Previous.getRepresentativeDecl()->getDeclContext();
13585 } else {
13586 // This is ill-formed, but provide the context that we would have
13587 // declared the function in, if we were permitted to, for error recovery.
13588 DC = FunctionContainingLocalClass;
13589 }
Richard Smith541b38b2013-09-20 01:15:31 +000013590 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013591
13592 // C++ [class.friend]p6:
13593 // A function can be defined in a friend declaration of a class if and
13594 // only if the class is a non-local class (9.8), the function name is
13595 // unqualified, and the function has namespace scope.
13596 if (D.isFunctionDefinition()) {
13597 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13598 }
13599
13600 // - There's no scope specifier, in which case we just go to the
13601 // appropriate scope and look for a function or function template
13602 // there as appropriate.
13603 } else if (SS.isInvalid() || !SS.isSet()) {
13604 // C++11 [namespace.memdef]p3:
13605 // If the name in a friend declaration is neither qualified nor
13606 // a template-id and the declaration is a function or an
13607 // elaborated-type-specifier, the lookup to determine whether
13608 // the entity has been previously declared shall not consider
13609 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013610 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013611
John McCallf7cfb222010-10-13 05:45:15 +000013612 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013613 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013614
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013615 // Skip class contexts. If someone can cite chapter and verse
13616 // for this behavior, that would be nice --- it's what GCC and
13617 // EDG do, and it seems like a reasonable intent, but the spec
13618 // really only says that checks for unqualified existing
13619 // declarations should stop at the nearest enclosing namespace,
13620 // not that they should only consider the nearest enclosing
13621 // namespace.
13622 while (DC->isRecord())
13623 DC = DC->getParent();
13624
13625 DeclContext *LookupDC = DC;
13626 while (LookupDC->isTransparentContext())
13627 LookupDC = LookupDC->getParent();
13628
13629 while (true) {
13630 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013631
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013632 if (!Previous.empty()) {
13633 DC = LookupDC;
13634 break;
John McCallf4776592010-10-14 22:22:28 +000013635 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013636
13637 if (isTemplateId) {
13638 if (isa<TranslationUnitDecl>(LookupDC)) break;
13639 } else {
13640 if (LookupDC->isFileContext()) break;
13641 }
13642 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013643 }
13644
John McCallccbc0322010-10-13 06:22:15 +000013645 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013646
John McCallde3fd222010-10-12 23:13:28 +000013647 // - There's a non-dependent scope specifier, in which case we
13648 // compute it and do a previous lookup there for a function
13649 // or function template.
13650 } else if (!SS.getScopeRep()->isDependent()) {
13651 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013652 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013653
Craig Topperc3ec1492014-05-26 06:22:03 +000013654 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013655
13656 LookupQualifiedName(Previous, DC);
13657
13658 // Ignore things found implicitly in the wrong scope.
13659 // TODO: better diagnostics for this case. Suggesting the right
13660 // qualified scope would be nice...
13661 LookupResult::Filter F = Previous.makeFilter();
13662 while (F.hasNext()) {
13663 NamedDecl *D = F.next();
13664 if (!DC->InEnclosingNamespaceSetOf(
13665 D->getDeclContext()->getRedeclContext()))
13666 F.erase();
13667 }
13668 F.done();
13669
13670 if (Previous.empty()) {
13671 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013672 Diag(Loc, diag::err_qualified_friend_not_found)
13673 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013674 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013675 }
13676
13677 // C++ [class.friend]p1: A friend of a class is a function or
13678 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013679 if (DC->Equals(CurContext))
13680 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013681 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013682 diag::warn_cxx98_compat_friend_is_member :
13683 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013684
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013685 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013686 // C++ [class.friend]p6:
13687 // A function can be defined in a friend declaration of a class if and
13688 // only if the class is a non-local class (9.8), the function name is
13689 // unqualified, and the function has namespace scope.
13690 SemaDiagnosticBuilder DB
13691 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13692
13693 DB << SS.getScopeRep();
13694 if (DC->isFileContext())
13695 DB << FixItHint::CreateRemoval(SS.getRange());
13696 SS.clear();
13697 }
John McCallde3fd222010-10-12 23:13:28 +000013698
13699 // - There's a scope specifier that does not match any template
13700 // parameter lists, in which case we use some arbitrary context,
13701 // create a method or method template, and wait for instantiation.
13702 // - There's a scope specifier that does match some template
13703 // parameter lists, which we don't handle right now.
13704 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013705 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013706 // C++ [class.friend]p6:
13707 // A function can be defined in a friend declaration of a class if and
13708 // only if the class is a non-local class (9.8), the function name is
13709 // unqualified, and the function has namespace scope.
13710 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13711 << SS.getScopeRep();
13712 }
13713
John McCallde3fd222010-10-12 23:13:28 +000013714 DC = CurContext;
13715 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013716 }
David Majnemere14d5302015-09-30 22:07:43 +000013717
John McCallf7cfb222010-10-13 05:45:15 +000013718 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013719 int DiagArg = -1;
13720 switch (D.getName().getKind()) {
13721 case UnqualifiedId::IK_ConstructorTemplateId:
13722 case UnqualifiedId::IK_ConstructorName:
13723 DiagArg = 0;
13724 break;
13725 case UnqualifiedId::IK_DestructorName:
13726 DiagArg = 1;
13727 break;
13728 case UnqualifiedId::IK_ConversionFunctionId:
13729 DiagArg = 2;
13730 break;
13731 case UnqualifiedId::IK_Identifier:
13732 case UnqualifiedId::IK_ImplicitSelfParam:
13733 case UnqualifiedId::IK_LiteralOperatorId:
13734 case UnqualifiedId::IK_OperatorFunctionId:
13735 case UnqualifiedId::IK_TemplateId:
13736 break;
David Majnemere14d5302015-09-30 22:07:43 +000013737 }
John McCall07e91c02009-08-06 02:15:43 +000013738 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013739 if (DiagArg >= 0) {
13740 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013741 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013742 }
John McCall07e91c02009-08-06 02:15:43 +000013743 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013744
Douglas Gregordd847ba2011-11-03 16:37:14 +000013745 // FIXME: This is an egregious hack to cope with cases where the scope stack
13746 // does not contain the declaration context, i.e., in an out-of-line
13747 // definition of a class.
13748 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13749 if (!DCScope) {
13750 FakeDCScope.setEntity(DC);
13751 DCScope = &FakeDCScope;
13752 }
Richard Smith114394f2013-08-09 04:35:01 +000013753
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013754 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013755 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013756 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013757 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013758
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013759 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013760
Richard Smith114394f2013-08-09 04:35:01 +000013761 // If we performed typo correction, we might have added a scope specifier
13762 // and changed the decl context.
13763 DC = ND->getDeclContext();
13764
John McCall759e32b2009-08-31 22:39:49 +000013765 // Add the function declaration to the appropriate lookup tables,
13766 // adjusting the redeclarations list as necessary. We don't
13767 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013768 //
John McCall759e32b2009-08-31 22:39:49 +000013769 // Also update the scope-based lookup if the target context's
13770 // lookup context is in lexical scope.
13771 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013772 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013773 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013774 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013775 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013776 }
John McCallaa74a0c2009-08-28 07:59:38 +000013777
13778 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013779 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013780 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013781 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013782 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013783
John McCalla0a96892012-08-10 03:15:35 +000013784 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013785 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013786 } else {
13787 if (DC->isRecord()) CheckFriendAccess(ND);
13788
John McCall2c2eb122010-10-16 06:59:13 +000013789 FunctionDecl *FD;
13790 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13791 FD = FTD->getTemplatedDecl();
13792 else
13793 FD = cast<FunctionDecl>(ND);
13794
David Majnemer502b0ed2013-06-25 23:09:30 +000013795 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13796 // default argument expression, that declaration shall be a definition
13797 // and shall be the only declaration of the function or function
13798 // template in the translation unit.
13799 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013800 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013801 // if we're in a dependent context. If the function is known to be a
13802 // redeclaration, we will have narrowed Previous down to the right decl.
13803 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013804 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013805 Diag(Previous.getRepresentativeDecl()->getLocation(),
13806 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013807 } else if (!D.isFunctionDefinition())
13808 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13809 }
13810
John McCall2c2eb122010-10-16 06:59:13 +000013811 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013812 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13813 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13814 << SS.getScopeRep() << SS.getRange()
13815 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013816 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013817 }
John McCall2c2eb122010-10-16 06:59:13 +000013818 }
John McCallde3fd222010-10-12 23:13:28 +000013819
John McCall48871652010-08-21 09:40:31 +000013820 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013821}
13822
John McCall48871652010-08-21 09:40:31 +000013823void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13824 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013825
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013826 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013827 if (!Fn) {
13828 Diag(DelLoc, diag::err_deleted_non_function);
13829 return;
13830 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013831
Douglas Gregorec9fd132012-01-14 16:38:05 +000013832 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013833 // Don't consider the implicit declaration we generate for explicit
13834 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013835 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13836 Prev->getPreviousDecl()) &&
13837 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013838 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013839 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13840 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13841 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013842 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013843 // If the declaration wasn't the first, we delete the function anyway for
13844 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013845 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013846 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013847
Nico Rieck9de0a572014-05-29 16:51:19 +000013848 // dllimport/dllexport cannot be deleted.
13849 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13850 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13851 Fn->setInvalidDecl();
13852 }
13853
Richard Smithb4d2a152013-04-02 19:38:47 +000013854 if (Fn->isDeleted())
13855 return;
13856
13857 // See if we're deleting a function which is already known to override a
13858 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013859 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013860 bool IssuedDiagnostic = false;
13861 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13862 E = MD->end_overridden_methods();
13863 I != E; ++I) {
13864 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13865 if (!IssuedDiagnostic) {
13866 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13867 IssuedDiagnostic = true;
13868 }
13869 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13870 }
13871 }
Richard Smithf3cec652016-10-31 18:18:29 +000013872 // If this function was implicitly deleted because it was defaulted,
13873 // explain why it was deleted.
13874 if (IssuedDiagnostic && MD->isDefaulted())
13875 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13876 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000013877 }
13878
Richard Smithb63b6ee2014-01-22 01:43:19 +000013879 // C++11 [basic.start.main]p3:
13880 // A program that defines main as deleted [...] is ill-formed.
13881 if (Fn->isMain())
13882 Diag(DelLoc, diag::err_deleted_main);
13883
Eric Fiselier525a3512016-10-31 23:07:15 +000013884 // C++11 [dcl.fct.def.delete]p4:
13885 // A deleted function is implicitly inline.
13886 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013887 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013888}
Sebastian Redl4c018662009-04-27 21:33:24 +000013889
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013890void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013891 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013892
13893 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013894 if (MD->getParent()->isDependentType()) {
13895 MD->setDefaulted();
13896 MD->setExplicitlyDefaulted();
13897 return;
13898 }
13899
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013900 CXXSpecialMember Member = getSpecialMember(MD);
13901 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013902 if (!MD->isInvalidDecl())
13903 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013904 return;
13905 }
13906
13907 MD->setDefaulted();
13908 MD->setExplicitlyDefaulted();
13909
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013910 // If this definition appears within the record, do the checking when
13911 // the record is complete.
13912 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013913 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013914 // Ask the template instantiation pattern that actually had the
13915 // '= default' on it.
13916 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013917
Richard Smith3901dfe2013-03-27 00:22:47 +000013918 // If the method was defaulted on its first declaration, we will have
13919 // already performed the checking in CheckCompletedCXXClass. Such a
13920 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013921 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013922 return;
13923
Richard Smithd3b5c9082012-07-27 04:22:15 +000013924 CheckExplicitlyDefaultedSpecialMember(MD);
13925
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013926 if (!MD->isInvalidDecl())
13927 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013928 } else {
13929 Diag(DefaultLoc, diag::err_default_special_members);
13930 }
13931}
13932
Sebastian Redl4c018662009-04-27 21:33:24 +000013933static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013934 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013935 if (!SubStmt)
13936 continue;
13937 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013938 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000013939 diag::err_return_in_constructor_handler);
13940 if (!isa<Expr>(SubStmt))
13941 SearchForReturnInStmt(Self, SubStmt);
13942 }
13943}
13944
13945void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13946 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13947 CXXCatchStmt *Handler = TryBlock->getHandler(I);
13948 SearchForReturnInStmt(*this, Handler);
13949 }
13950}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013951
David Blaikie68f71a32013-01-18 23:03:15 +000013952bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000013953 const CXXMethodDecl *Old) {
13954 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13955 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13956
13957 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13958
13959 // If the calling conventions match, everything is fine
13960 if (NewCC == OldCC)
13961 return false;
13962
Hans Wennborg2545efe2013-12-11 17:42:11 +000013963 // If the calling conventions mismatch because the new function is static,
13964 // suppress the calling convention mismatch error; the error about static
13965 // function override (err_static_overrides_virtual from
13966 // Sema::CheckFunctionDeclaration) is more clear.
13967 if (New->getStorageClass() == SC_Static)
13968 return false;
13969
Reid Kleckner78af0702013-08-27 23:08:25 +000013970 Diag(New->getLocation(),
13971 diag::err_conflicting_overriding_cc_attributes)
13972 << New->getDeclName() << New->getType() << Old->getType();
13973 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13974 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000013975}
13976
Mike Stump11289f42009-09-09 15:08:12 +000013977bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013978 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000013979 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13980 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013981
Chandler Carruth284bb2e2010-02-15 11:53:20 +000013982 if (Context.hasSameType(NewTy, OldTy) ||
13983 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013984 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013985
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013986 // Check if the return types are covariant
13987 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000013988
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013989 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013990 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13991 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013992 NewClassTy = NewPT->getPointeeType();
13993 OldClassTy = OldPT->getPointeeType();
13994 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013995 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13996 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13997 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13998 NewClassTy = NewRT->getPointeeType();
13999 OldClassTy = OldRT->getPointeeType();
14000 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014001 }
14002 }
Mike Stump11289f42009-09-09 15:08:12 +000014003
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014004 // The return types aren't either both pointers or references to a class type.
14005 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014006 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014007 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014008 << New->getDeclName() << NewTy << OldTy
14009 << New->getReturnTypeSourceRange();
14010 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14011 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014012
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014013 return true;
14014 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014015
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014016 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014017 // C++14 [class.virtual]p8:
14018 // If the class type in the covariant return type of D::f differs from
14019 // that of B::f, the class type in the return type of D::f shall be
14020 // complete at the point of declaration of D::f or shall be the class
14021 // type D.
14022 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14023 if (!RT->isBeingDefined() &&
14024 RequireCompleteType(New->getLocation(), NewClassTy,
14025 diag::err_covariant_return_incomplete,
14026 New->getDeclName()))
14027 return true;
14028 }
14029
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014030 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014031 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014032 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14033 << New->getDeclName() << NewTy << OldTy
14034 << New->getReturnTypeSourceRange();
14035 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14036 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014037 return true;
14038 }
Mike Stump11289f42009-09-09 15:08:12 +000014039
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014040 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014041 if (CheckDerivedToBaseConversion(
14042 NewClassTy, OldClassTy,
14043 diag::err_covariant_return_inaccessible_base,
14044 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14045 New->getLocation(), New->getReturnTypeSourceRange(),
14046 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014047 // FIXME: this note won't trigger for delayed access control
14048 // diagnostics, and it's impossible to get an undelayed error
14049 // here from access control during the original parse because
14050 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014051 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14052 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014053 return true;
14054 }
14055 }
Mike Stump11289f42009-09-09 15:08:12 +000014056
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014057 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014058 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014059 Diag(New->getLocation(),
14060 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014061 << New->getDeclName() << NewTy << OldTy
14062 << New->getReturnTypeSourceRange();
14063 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14064 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014065 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014066 }
Mike Stump11289f42009-09-09 15:08:12 +000014067
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014068
14069 // The new class type must have the same or less qualifiers as the old type.
14070 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14071 Diag(New->getLocation(),
14072 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014073 << New->getDeclName() << NewTy << OldTy
14074 << New->getReturnTypeSourceRange();
14075 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14076 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014077 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014078 }
Mike Stump11289f42009-09-09 15:08:12 +000014079
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014080 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014081}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014082
Douglas Gregor21920e372009-12-01 17:24:26 +000014083/// \brief Mark the given method pure.
14084///
14085/// \param Method the method to be marked pure.
14086///
14087/// \param InitRange the source range that covers the "0" initializer.
14088bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014089 SourceLocation EndLoc = InitRange.getEnd();
14090 if (EndLoc.isValid())
14091 Method->setRangeEnd(EndLoc);
14092
Douglas Gregor21920e372009-12-01 17:24:26 +000014093 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14094 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014095 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014096 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014097
14098 if (!Method->isInvalidDecl())
14099 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14100 << Method->getDeclName() << InitRange;
14101 return true;
14102}
14103
Richard Smith9ba0fec2015-06-30 01:28:56 +000014104void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14105 if (D->getFriendObjectKind())
14106 Diag(D->getLocation(), diag::err_pure_friend);
14107 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14108 CheckPureMethod(M, ZeroLoc);
14109 else
14110 Diag(D->getLocation(), diag::err_illegal_initializer);
14111}
14112
Douglas Gregor926410d2012-02-21 02:22:07 +000014113/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014114static bool isStaticDataMember(const Decl *D) {
14115 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14116 return Var->isStaticDataMember();
14117
14118 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014119}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014120
John McCall1f4ee7b2009-12-19 09:28:58 +000014121/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14122/// an initializer for the out-of-line declaration 'Dcl'. The scope
14123/// is a fresh scope pushed for just this purpose.
14124///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014125/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14126/// static data member of class X, names should be looked up in the scope of
14127/// class X.
John McCall48871652010-08-21 09:40:31 +000014128void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014129 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014130 if (!D || D->isInvalidDecl())
14131 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014132
Richard Smitha2302242013-12-05 07:51:02 +000014133 // We will always have a nested name specifier here, but this declaration
14134 // might not be out of line if the specifier names the current namespace:
14135 // extern int n;
14136 // int ::n = 0;
14137 if (D->isOutOfLine())
14138 EnterDeclaratorContext(S, D->getDeclContext());
14139
Douglas Gregor926410d2012-02-21 02:22:07 +000014140 // If we are parsing the initializer for a static data member, push a
14141 // new expression evaluation context that is associated with this static
14142 // data member.
14143 if (isStaticDataMember(D))
14144 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014145}
14146
14147/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014148/// initializer for the out-of-line declaration 'D'.
14149void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014150 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014151 if (!D || D->isInvalidDecl())
14152 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014153
Douglas Gregor926410d2012-02-21 02:22:07 +000014154 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014155 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014156
Richard Smitha2302242013-12-05 07:51:02 +000014157 if (D->isOutOfLine())
14158 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014159}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014160
14161/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14162/// C++ if/switch/while/for statement.
14163/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014164DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014165 // C++ 6.4p2:
14166 // The declarator shall not specify a function or an array.
14167 // The type-specifier-seq shall not contain typedef and shall not declare a
14168 // new class or enumeration.
14169 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14170 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014171
14172 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014173 if (!Dcl)
14174 return true;
14175
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014176 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14177 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014178 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014179 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014180 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014181
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014182 return Dcl;
14183}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014184
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014185void Sema::LoadExternalVTableUses() {
14186 if (!ExternalSource)
14187 return;
14188
14189 SmallVector<ExternalVTableUse, 4> VTables;
14190 ExternalSource->ReadUsedVTables(VTables);
14191 SmallVector<VTableUse, 4> NewUses;
14192 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14193 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14194 = VTablesUsed.find(VTables[I].Record);
14195 // Even if a definition wasn't required before, it may be required now.
14196 if (Pos != VTablesUsed.end()) {
14197 if (!Pos->second && VTables[I].DefinitionRequired)
14198 Pos->second = true;
14199 continue;
14200 }
14201
14202 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14203 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14204 }
14205
14206 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14207}
14208
Douglas Gregor88d292c2010-05-13 16:44:06 +000014209void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14210 bool DefinitionRequired) {
14211 // Ignore any vtable uses in unevaluated operands or for classes that do
14212 // not have a vtable.
14213 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014214 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014215 return;
14216
Douglas Gregor88d292c2010-05-13 16:44:06 +000014217 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014218 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014219 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14220 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14221 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14222 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014223 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014224 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014225 // list, since we may have already processed the first entry.
14226 if (DefinitionRequired && !Pos.first->second) {
14227 Pos.first->second = true;
14228 } else {
14229 // Otherwise, we can early exit.
14230 return;
14231 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014232 } else {
14233 // The Microsoft ABI requires that we perform the destructor body
14234 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14235 // the deleting destructor is emitted with the vtable, not with the
14236 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014237 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014238 CXXDestructorDecl *DD = Class->getDestructor();
14239 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14240 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14241 // If this is an out-of-line declaration, marking it referenced will
14242 // not do anything. Manually call CheckDestructor to look up operator
14243 // delete().
14244 ContextRAII SavedContext(*this, DD);
14245 CheckDestructor(DD);
14246 } else {
14247 MarkFunctionReferenced(Loc, Class->getDestructor());
14248 }
Hans Wennborg34804352016-04-13 20:21:15 +000014249 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014250 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014251 }
14252
14253 // Local classes need to have their virtual members marked
14254 // immediately. For all other classes, we mark their virtual members
14255 // at the end of the translation unit.
14256 if (Class->isLocalClass())
14257 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014258 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014259 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014260}
14261
Douglas Gregor88d292c2010-05-13 16:44:06 +000014262bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014263 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014264 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014265 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014266
Douglas Gregor88d292c2010-05-13 16:44:06 +000014267 // Note: The VTableUses vector could grow as a result of marking
14268 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014269 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014270 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014271 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014272 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014273 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014274 if (!Class)
14275 continue;
14276
14277 SourceLocation Loc = VTableUses[I].second;
14278
Richard Smithd3b5c9082012-07-27 04:22:15 +000014279 bool DefineVTable = true;
14280
Douglas Gregor88d292c2010-05-13 16:44:06 +000014281 // If this class has a key function, but that key function is
14282 // defined in another translation unit, we don't need to emit the
14283 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014284 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014285 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014286 // The key function is in another translation unit.
14287 DefineVTable = false;
14288 TemplateSpecializationKind TSK =
14289 KeyFunction->getTemplateSpecializationKind();
14290 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14291 TSK != TSK_ImplicitInstantiation &&
14292 "Instantiations don't have key functions");
14293 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014294 } else if (!KeyFunction) {
14295 // If we have a class with no key function that is the subject
14296 // of an explicit instantiation declaration, suppress the
14297 // vtable; it will live with the explicit instantiation
14298 // definition.
14299 bool IsExplicitInstantiationDeclaration
14300 = Class->getTemplateSpecializationKind()
14301 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014302 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014303 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014304 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014305 if (TSK == TSK_ExplicitInstantiationDeclaration)
14306 IsExplicitInstantiationDeclaration = true;
14307 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14308 IsExplicitInstantiationDeclaration = false;
14309 break;
14310 }
14311 }
14312
14313 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014314 DefineVTable = false;
14315 }
14316
14317 // The exception specifications for all virtual members may be needed even
14318 // if we are not providing an authoritative form of the vtable in this TU.
14319 // We may choose to emit it available_externally anyway.
14320 if (!DefineVTable) {
14321 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14322 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014323 }
14324
14325 // Mark all of the virtual members of this class as referenced, so
14326 // that we can build a vtable. Then, tell the AST consumer that a
14327 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014328 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014329 MarkVirtualMembersReferenced(Loc, Class);
14330 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014331 if (VTablesUsed[Canonical])
14332 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014333
14334 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000014335 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000014336 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014337 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000014338 if (!KeyFunction ||
14339 (KeyFunction->hasBody(KeyFunctionDef) &&
14340 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000014341 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14342 TSK_ExplicitInstantiationDefinition
14343 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14344 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014345 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014346 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014347 VTableUses.clear();
14348
Douglas Gregor97509692011-04-22 22:25:37 +000014349 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014350}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014351
Richard Smithd3b5c9082012-07-27 04:22:15 +000014352void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14353 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014354 for (const auto *I : RD->methods())
14355 if (I->isVirtual() && !I->isPure())
14356 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014357}
14358
Rafael Espindola5b334082010-03-26 00:36:59 +000014359void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14360 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014361 // Mark all functions which will appear in RD's vtable as used.
14362 CXXFinalOverriderMap FinalOverriders;
14363 RD->getFinalOverriders(FinalOverriders);
14364 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14365 E = FinalOverriders.end();
14366 I != E; ++I) {
14367 for (OverridingMethods::const_iterator OI = I->second.begin(),
14368 OE = I->second.end();
14369 OI != OE; ++OI) {
14370 assert(OI->second.size() > 0 && "no final overrider");
14371 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014372
Richard Smith4ff9ff92012-07-07 06:59:51 +000014373 // C++ [basic.def.odr]p2:
14374 // [...] A virtual member function is used if it is not pure. [...]
14375 if (!Overrider->isPure())
14376 MarkFunctionReferenced(Loc, Overrider);
14377 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014378 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014379
14380 // Only classes that have virtual bases need a VTT.
14381 if (RD->getNumVBases() == 0)
14382 return;
14383
Aaron Ballman574705e2014-03-13 15:41:46 +000014384 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014385 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014386 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014387 if (Base->getNumVBases() == 0)
14388 continue;
14389 MarkVirtualMembersReferenced(Loc, Base);
14390 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014391}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014392
14393/// SetIvarInitializers - This routine builds initialization ASTs for the
14394/// Objective-C implementation whose ivars need be initialized.
14395void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014396 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014397 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014398 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014399 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014400 CollectIvarsToConstructOrDestruct(OID, ivars);
14401 if (ivars.empty())
14402 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014403 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014404 for (unsigned i = 0; i < ivars.size(); i++) {
14405 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014406 if (Field->isInvalidDecl())
14407 continue;
14408
Alexis Hunt1d792652011-01-08 20:30:50 +000014409 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014410 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14411 InitializationKind InitKind =
14412 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014413
14414 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14415 ExprResult MemberInit =
14416 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014417 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014418 // Note, MemberInit could actually come back empty if no initialization
14419 // is required (e.g., because it would call a trivial default constructor)
14420 if (!MemberInit.get() || MemberInit.isInvalid())
14421 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014422
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014423 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014424 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14425 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014426 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014427 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014428 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014429
14430 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014431 if (const RecordType *RecordTy =
14432 Context.getBaseElementType(Field->getType())
14433 ->getAs<RecordType>()) {
14434 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014435 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014436 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014437 CheckDestructorAccess(Field->getLocation(), Destructor,
14438 PDiag(diag::err_access_dtor_ivar)
14439 << Context.getBaseElementType(Field->getType()));
14440 }
14441 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014442 }
14443 ObjCImplementation->setIvarInitializers(Context,
14444 AllToInit.data(), AllToInit.size());
14445 }
14446}
Alexis Hunt6118d662011-05-04 05:57:24 +000014447
Alexis Hunt27a761d2011-05-04 23:29:54 +000014448static
14449void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14450 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14451 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14452 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14453 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014454 if (Ctor->isInvalidDecl())
14455 return;
14456
Richard Smith802c4b72012-08-23 06:16:52 +000014457 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14458
14459 // Target may not be determinable yet, for instance if this is a dependent
14460 // call in an uninstantiated template.
14461 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014462 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014463 (void)Target->hasBody(FNTarget);
14464 Target = const_cast<CXXConstructorDecl*>(
14465 cast_or_null<CXXConstructorDecl>(FNTarget));
14466 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014467
14468 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14469 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014470 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014471
David Blaikie82e95a32014-11-19 07:49:47 +000014472 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014473 return;
14474
14475 // We know that beyond here, we aren't chaining into a cycle.
14476 if (!Target || !Target->isDelegatingConstructor() ||
14477 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014478 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014479 Current.clear();
14480 // We've hit a cycle.
14481 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14482 Current.count(TCanonical)) {
14483 // If we haven't diagnosed this cycle yet, do so now.
14484 if (!Invalid.count(TCanonical)) {
14485 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014486 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014487 << Ctor;
14488
Richard Smith802c4b72012-08-23 06:16:52 +000014489 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014490 if (TCanonical != Canonical)
14491 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14492
14493 CXXConstructorDecl *C = Target;
14494 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014495 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014496 (void)C->getTargetConstructor()->hasBody(FNTarget);
14497 assert(FNTarget && "Ctor cycle through bodiless function");
14498
Richard Smith802c4b72012-08-23 06:16:52 +000014499 C = const_cast<CXXConstructorDecl*>(
14500 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014501 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14502 }
14503 }
14504
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014505 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014506 Current.clear();
14507 } else {
14508 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14509 }
14510}
14511
14512
Alexis Hunt6118d662011-05-04 05:57:24 +000014513void Sema::CheckDelegatingCtorCycles() {
14514 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14515
Douglas Gregorbae31202011-07-27 21:57:17 +000014516 for (DelegatingCtorDeclsType::iterator
14517 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014518 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014519 I != E; ++I)
14520 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014521
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014522 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14523 CE = Invalid.end();
14524 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014525 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014526}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014527
Douglas Gregor3024f072012-04-16 07:05:22 +000014528namespace {
14529 /// \brief AST visitor that finds references to the 'this' expression.
14530 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14531 Sema &S;
14532
14533 public:
14534 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14535
14536 bool VisitCXXThisExpr(CXXThisExpr *E) {
14537 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14538 << E->isImplicit();
14539 return false;
14540 }
14541 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014542}
Douglas Gregor3024f072012-04-16 07:05:22 +000014543
14544bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14545 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14546 if (!TSInfo)
14547 return false;
14548
14549 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014550 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014551 if (!ProtoTL)
14552 return false;
14553
14554 // C++11 [expr.prim.general]p3:
14555 // [The expression this] shall not appear before the optional
14556 // cv-qualifier-seq and it shall not appear within the declaration of a
14557 // static member function (although its type and value category are defined
14558 // within a static member function as they are within a non-static member
14559 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014560 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014561 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014562 FindCXXThisExpr Finder(*this);
14563
14564 // If the return type came after the cv-qualifier-seq, check it now.
14565 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014566 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014567 return true;
14568
14569 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014570 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14571 return true;
14572
14573 return checkThisInStaticMemberFunctionAttributes(Method);
14574}
14575
14576bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14577 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14578 if (!TSInfo)
14579 return false;
14580
14581 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014582 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014583 if (!ProtoTL)
14584 return false;
14585
David Blaikie6adc78e2013-02-18 22:06:02 +000014586 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014587 FindCXXThisExpr Finder(*this);
14588
Douglas Gregor3024f072012-04-16 07:05:22 +000014589 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014590 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014591 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014592 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014593 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014594 case EST_DynamicNone:
14595 case EST_MSAny:
14596 case EST_None:
14597 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014598
Douglas Gregor3024f072012-04-16 07:05:22 +000014599 case EST_ComputedNoexcept:
14600 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14601 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014602
Douglas Gregor3024f072012-04-16 07:05:22 +000014603 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014604 for (const auto &E : Proto->exceptions()) {
14605 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014606 return true;
14607 }
14608 break;
14609 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014610
14611 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014612}
14613
14614bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14615 FindCXXThisExpr Finder(*this);
14616
14617 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014618 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014619 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014620 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014621 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014622 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014623 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014624 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014625 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014626 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014627 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014628 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014629 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014630 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014631 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014632 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014633 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014634 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014635 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014636 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014637 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014638 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014639 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014640 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014641 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014642 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014643 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014644 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014645 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014646 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014647 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014648
14649 if (Arg && !Finder.TraverseStmt(Arg))
14650 return true;
14651
14652 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14653 if (!Finder.TraverseStmt(Args[I]))
14654 return true;
14655 }
14656 }
14657
14658 return false;
14659}
14660
Richard Smith2e321552014-11-12 02:00:47 +000014661void Sema::checkExceptionSpecification(
14662 bool IsTopLevel, ExceptionSpecificationType EST,
14663 ArrayRef<ParsedType> DynamicExceptions,
14664 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14665 SmallVectorImpl<QualType> &Exceptions,
14666 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014667 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014668 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014669 if (EST == EST_Dynamic) {
14670 Exceptions.reserve(DynamicExceptions.size());
14671 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14672 // FIXME: Preserve type source info.
14673 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14674
Richard Smith2e321552014-11-12 02:00:47 +000014675 if (IsTopLevel) {
14676 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14677 collectUnexpandedParameterPacks(ET, Unexpanded);
14678 if (!Unexpanded.empty()) {
14679 DiagnoseUnexpandedParameterPacks(
14680 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14681 Unexpanded);
14682 continue;
14683 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014684 }
14685
14686 // Check that the type is valid for an exception spec, and
14687 // drop it if not.
14688 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14689 Exceptions.push_back(ET);
14690 }
Richard Smith8acb4282014-07-31 21:57:55 +000014691 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014692 return;
14693 }
Richard Smith8acb4282014-07-31 21:57:55 +000014694
Douglas Gregor433e0532012-04-16 18:27:27 +000014695 if (EST == EST_ComputedNoexcept) {
14696 // If an error occurred, there's no expression here.
14697 if (NoexceptExpr) {
14698 assert((NoexceptExpr->isTypeDependent() ||
14699 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14700 Context.BoolTy) &&
14701 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014702 if (IsTopLevel && NoexceptExpr &&
14703 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014704 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014705 return;
14706 }
Richard Smith8acb4282014-07-31 21:57:55 +000014707
Douglas Gregor433e0532012-04-16 18:27:27 +000014708 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014709 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014710 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014711 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014712 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014713 }
14714 return;
14715 }
14716}
14717
Richard Smith0b3a4622014-11-13 20:01:57 +000014718void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14719 ExceptionSpecificationType EST,
14720 SourceRange SpecificationRange,
14721 ArrayRef<ParsedType> DynamicExceptions,
14722 ArrayRef<SourceRange> DynamicExceptionRanges,
14723 Expr *NoexceptExpr) {
14724 if (!MethodD)
14725 return;
14726
14727 // Dig out the method we're referring to.
14728 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14729 MethodD = FunTmpl->getTemplatedDecl();
14730
14731 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14732 if (!Method)
14733 return;
14734
14735 // Check the exception specification.
14736 llvm::SmallVector<QualType, 4> Exceptions;
14737 FunctionProtoType::ExceptionSpecInfo ESI;
14738 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14739 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14740 ESI);
14741
14742 // Update the exception specification on the function type.
14743 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14744
14745 if (Method->isStatic())
14746 checkThisInStaticMemberFunctionExceptionSpec(Method);
14747
14748 if (Method->isVirtual()) {
14749 // Check overrides, which we previously had to delay.
14750 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14751 OEnd = Method->end_overridden_methods();
14752 O != OEnd; ++O)
14753 CheckOverridingFunctionExceptionSpec(Method, *O);
14754 }
14755}
14756
John McCall5e77d762013-04-16 07:28:30 +000014757/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14758///
14759MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14760 SourceLocation DeclStart,
14761 Declarator &D, Expr *BitWidth,
14762 InClassInitStyle InitStyle,
14763 AccessSpecifier AS,
14764 AttributeList *MSPropertyAttr) {
14765 IdentifierInfo *II = D.getIdentifier();
14766 if (!II) {
14767 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014768 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014769 }
14770 SourceLocation Loc = D.getIdentifierLoc();
14771
14772 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14773 QualType T = TInfo->getType();
14774 if (getLangOpts().CPlusPlus) {
14775 CheckExtraCXXDefaultArguments(D);
14776
14777 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14778 UPPC_DataMemberType)) {
14779 D.setInvalidType();
14780 T = Context.IntTy;
14781 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14782 }
14783 }
14784
14785 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14786
Richard Smith62f19e72016-06-25 00:15:56 +000014787 if (D.getDeclSpec().isInlineSpecified())
14788 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14789 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014790 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14791 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14792 diag::err_invalid_thread)
14793 << DeclSpec::getSpecifierName(TSCS);
14794
14795 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014796 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014797 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14798 LookupName(Previous, S);
14799 switch (Previous.getResultKind()) {
14800 case LookupResult::Found:
14801 case LookupResult::FoundUnresolvedValue:
14802 PrevDecl = Previous.getAsSingle<NamedDecl>();
14803 break;
14804
14805 case LookupResult::FoundOverloaded:
14806 PrevDecl = Previous.getRepresentativeDecl();
14807 break;
14808
14809 case LookupResult::NotFound:
14810 case LookupResult::NotFoundInCurrentInstantiation:
14811 case LookupResult::Ambiguous:
14812 break;
14813 }
14814
14815 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14816 // Maybe we will complain about the shadowed template parameter.
14817 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14818 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014819 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014820 }
14821
14822 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014823 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014824
14825 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014826 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014827 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14828 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014829 ProcessDeclAttributes(TUScope, NewPD, D);
14830 NewPD->setAccess(AS);
14831
14832 if (NewPD->isInvalidDecl())
14833 Record->setInvalidDecl();
14834
14835 if (D.getDeclSpec().isModulePrivateSpecified())
14836 NewPD->setModulePrivate();
14837
14838 if (NewPD->isInvalidDecl() && PrevDecl) {
14839 // Don't introduce NewFD into scope; there's already something
14840 // with the same name in the same scope.
14841 } else if (II) {
14842 PushOnScopeChains(NewPD, S);
14843 } else
14844 Record->addDecl(NewPD);
14845
14846 return NewPD;
14847}