blob: fc37727344c4996c7b44fe793129d9ac62b04287 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355}
356
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Alp Tokerc5350722014-02-26 22:27:52 +0000381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000395 }
396 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemer502b0ed2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Toppere4794282012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloye9430032012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000463
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000484
Francois Pichet8cb243a2011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCalle61b02b2010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smith58c3cc12012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
Richard Smith5b8b3db2012-02-20 23:28:05 +0000587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000588 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 if (New->isConstexpr() != Old->isConstexpr()) {
591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592 << New << New->isConstexpr();
593 Diag(Old->getLocation(), diag::note_previous_declaration);
594 Invalid = true;
595 }
596
David Majnemer502b0ed2013-06-25 23:09:30 +0000597 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000598 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000599 // the only declaration of the function or function template in the
600 // translation unit.
601 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
602 functionDeclHasDefaultArgument(Old)) {
603 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
604 Diag(Old->getLocation(), diag::note_previous_declaration);
605 Invalid = true;
606 }
607
Douglas Gregorf40863c2010-02-12 07:32:17 +0000608 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000609 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000610
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000611 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000612}
613
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000614/// \brief Merge the exception specifications of two variable declarations.
615///
616/// This is called when there's a redeclaration of a VarDecl. The function
617/// checks if the redeclaration might have an exception specification and
618/// validates compatibility and merges the specs if necessary.
619void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
620 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000621 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622 return;
623
624 assert(Context.hasSameType(New->getType(), Old->getType()) &&
625 "Should only be called if types are otherwise the same.");
626
627 QualType NewType = New->getType();
628 QualType OldType = Old->getType();
629
630 // We're only interested in pointers and references to functions, as well
631 // as pointers to member functions.
632 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
633 NewType = R->getPointeeType();
634 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
635 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
636 NewType = P->getPointeeType();
637 OldType = OldType->getAs<PointerType>()->getPointeeType();
638 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
639 NewType = M->getPointeeType();
640 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
641 }
642
643 if (!NewType->isFunctionProtoType())
644 return;
645
646 // There's lots of special cases for functions. For function pointers, system
647 // libraries are hopefully not as broken so that we don't need these
648 // workarounds.
649 if (CheckEquivalentExceptionSpec(
650 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
651 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
652 New->setInvalidDecl();
653 }
654}
655
Chris Lattner199abbc2008-04-08 05:04:30 +0000656/// CheckCXXDefaultArguments - Verify that the default arguments for a
657/// function declaration are well-formed according to C++
658/// [dcl.fct.default].
659void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
660 unsigned NumParams = FD->getNumParams();
661 unsigned p;
662
663 // Find first parameter with a default argument
664 for (p = 0; p < NumParams; ++p) {
665 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000666 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000667 break;
668 }
669
670 // C++ [dcl.fct.default]p4:
671 // In a given function declaration, all parameters
672 // subsequent to a parameter with a default argument shall
673 // have default arguments supplied in this or previous
674 // declarations. A default argument shall not be redefined
675 // by a later declaration (not even to the same value).
676 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000677 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000678 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000679 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000680 if (Param->isInvalidDecl())
681 /* We already complained about this parameter. */;
682 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000684 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000685 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 else
Mike Stump11289f42009-09-09 15:08:12 +0000687 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Chris Lattner199abbc2008-04-08 05:04:30 +0000690 LastMissingDefaultArg = p;
691 }
692 }
693
694 if (LastMissingDefaultArg > 0) {
695 // Some default arguments were missing. Clear out all of the
696 // default arguments up to (and including) the last missing
697 // default argument, so that we leave the function parameters
698 // in a semantically valid state.
699 for (p = 0; p <= LastMissingDefaultArg; ++p) {
700 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000701 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000702 Param->setDefaultArg(0);
703 }
704 }
705 }
706}
Douglas Gregor556877c2008-04-13 21:30:24 +0000707
Richard Smitheb3c10c2011-10-01 02:31:28 +0000708// CheckConstexprParameterTypes - Check whether a function's parameter types
709// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000710// diagnostic and return false.
711static bool CheckConstexprParameterTypes(Sema &SemaRef,
712 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000713 unsigned ArgIndex = 0;
714 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000715 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
716 e = FT->param_type_end();
717 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000718 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
719 SourceLocation ParamLoc = PD->getLocation();
720 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000721 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000722 diag::err_constexpr_non_literal_param,
723 ArgIndex+1, PD->getSourceRange(),
724 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000725 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000727 return true;
728}
729
730/// \brief Get diagnostic %select index for tag kind for
731/// record diagnostic message.
732/// WARNING: Indexes apply to particular diagnostics only!
733///
734/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000735static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000736 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000737 case TTK_Struct: return 0;
738 case TTK_Interface: return 1;
739 case TTK_Class: return 2;
740 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000741 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000742}
743
744// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
745// the requirements of a constexpr function definition or a constexpr
746// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000747// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000748//
Richard Smith3607ffe2012-02-13 03:54:03 +0000749// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
750bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000751 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
752 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000753 // C++11 [dcl.constexpr]p4:
754 // The definition of a constexpr constructor shall satisfy the following
755 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000757 const CXXRecordDecl *RD = MD->getParent();
758 if (RD->getNumVBases()) {
759 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
760 << isa<CXXConstructorDecl>(NewFD)
761 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000762 for (const auto &I : RD->vbases())
763 Diag(I.getLocStart(),
764 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000765 return false;
766 }
Richard Smith7971b692012-01-13 04:54:00 +0000767 }
768
769 if (!isa<CXXConstructorDecl>(NewFD)) {
770 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000771 // The definition of a constexpr function shall satisfy the following
772 // constraints:
773 // - it shall not be virtual;
774 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
775 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000777
Richard Smith3607ffe2012-02-13 03:54:03 +0000778 // If it's not obvious why this function is virtual, find an overridden
779 // function which uses the 'virtual' keyword.
780 const CXXMethodDecl *WrittenVirtual = Method;
781 while (!WrittenVirtual->isVirtualAsWritten())
782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
783 if (WrittenVirtual != Method)
784 Diag(WrittenVirtual->getLocation(),
785 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000786 return false;
787 }
788
789 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000790 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000791 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000792 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000793 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000795 }
796
Richard Smith7971b692012-01-13 04:54:00 +0000797 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000798 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000799 return false;
800
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 return true;
802}
803
804/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000805/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000806///
Richard Smithd9f663b2013-04-22 15:31:51 +0000807/// \return true if the body is OK (maybe only as an extension), false if we
808/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000810 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
811 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000812 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
813 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000814 for (const auto *DclIt : DS->decls()) {
815 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 case Decl::StaticAssert:
817 case Decl::Using:
818 case Decl::UsingShadow:
819 case Decl::UsingDirective:
820 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000821 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822 // - static_assert-declarations
823 // - using-declarations,
824 // - using-directives,
825 continue;
826
827 case Decl::Typedef:
828 case Decl::TypeAlias: {
829 // - typedef declarations and alias-declarations that do not define
830 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000831 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
833 // Don't allow variably-modified types in constexpr functions.
834 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
835 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
836 << TL.getSourceRange() << TL.getType()
837 << isa<CXXConstructorDecl>(Dcl);
838 return false;
839 }
840 continue;
841 }
842
843 case Decl::Enum:
844 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000845 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000846 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000847 SemaRef.Diag(DS->getLocStart(),
848 SemaRef.getLangOpts().CPlusPlus1y
849 ? diag::warn_cxx11_compat_constexpr_type_definition
850 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000851 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000852 continue;
853
Richard Smithd9f663b2013-04-22 15:31:51 +0000854 case Decl::EnumConstant:
855 case Decl::IndirectField:
856 case Decl::ParmVar:
857 // These can only appear with other declarations which are banned in
858 // C++11 and permitted in C++1y, so ignore them.
859 continue;
860
861 case Decl::Var: {
862 // C++1y [dcl.constexpr]p3 allows anything except:
863 // a definition of a variable of non-literal type or of static or
864 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000865 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000866 if (VD->isThisDeclarationADefinition()) {
867 if (VD->isStaticLocal()) {
868 SemaRef.Diag(VD->getLocation(),
869 diag::err_constexpr_local_var_static)
870 << isa<CXXConstructorDecl>(Dcl)
871 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
872 return false;
873 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000874 if (!VD->getType()->isDependentType() &&
875 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 VD->getLocation(), VD->getType(),
877 diag::err_constexpr_local_var_non_literal_type,
878 isa<CXXConstructorDecl>(Dcl)))
879 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000880 if (!VD->getType()->isDependentType() &&
881 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000882 SemaRef.Diag(VD->getLocation(),
883 diag::err_constexpr_local_var_no_init)
884 << isa<CXXConstructorDecl>(Dcl);
885 return false;
886 }
887 }
888 SemaRef.Diag(VD->getLocation(),
889 SemaRef.getLangOpts().CPlusPlus1y
890 ? diag::warn_cxx11_compat_constexpr_local_var
891 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000892 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000893 continue;
894 }
895
896 case Decl::NamespaceAlias:
897 case Decl::Function:
898 // These are disallowed in C++11 and permitted in C++1y. Allow them
899 // everywhere as an extension.
900 if (!Cxx1yLoc.isValid())
901 Cxx1yLoc = DS->getLocStart();
902 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000903
904 default:
905 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
906 << isa<CXXConstructorDecl>(Dcl);
907 return false;
908 }
909 }
910
911 return true;
912}
913
914/// Check that the given field is initialized within a constexpr constructor.
915///
916/// \param Dcl The constexpr constructor being checked.
917/// \param Field The field being checked. This may be a member of an anonymous
918/// struct or union nested within the class being checked.
919/// \param Inits All declarations, including anonymous struct/union members and
920/// indirect members, for which any initialization was provided.
921/// \param Diagnosed Set to true if an error is produced.
922static void CheckConstexprCtorInitializer(Sema &SemaRef,
923 const FunctionDecl *Dcl,
924 FieldDecl *Field,
925 llvm::SmallSet<Decl*, 16> &Inits,
926 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000927 if (Field->isInvalidDecl())
928 return;
929
Douglas Gregor556e5862011-10-10 17:22:13 +0000930 if (Field->isUnnamedBitfield())
931 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000932
Richard Smithab44d5b2013-12-10 08:25:00 +0000933 // Anonymous unions with no variant members and empty anonymous structs do not
934 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
935 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000936 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000937 (Field->getType()->isUnionType()
938 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
939 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940 return;
941
Richard Smitheb3c10c2011-10-01 02:31:28 +0000942 if (!Inits.count(Field)) {
943 if (!Diagnosed) {
944 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
945 Diagnosed = true;
946 }
947 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
948 } else if (Field->isAnonymousStructOrUnion()) {
949 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000950 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000951 // If an anonymous union contains an anonymous struct of which any member
952 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000953 if (!RD->isUnion() || Inits.count(I))
954 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000955 }
956}
957
Richard Smithd9f663b2013-04-22 15:31:51 +0000958/// Check the provided statement is allowed in a constexpr function
959/// definition.
960static bool
961CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000962 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000963 SourceLocation &Cxx1yLoc) {
964 // - its function-body shall be [...] a compound-statement that contains only
965 switch (S->getStmtClass()) {
966 case Stmt::NullStmtClass:
967 // - null statements,
968 return true;
969
970 case Stmt::DeclStmtClass:
971 // - static_assert-declarations
972 // - using-declarations,
973 // - using-directives,
974 // - typedef declarations and alias-declarations that do not define
975 // classes or enumerations,
976 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
977 return false;
978 return true;
979
980 case Stmt::ReturnStmtClass:
981 // - and exactly one return statement;
982 if (isa<CXXConstructorDecl>(Dcl)) {
983 // C++1y allows return statements in constexpr constructors.
984 if (!Cxx1yLoc.isValid())
985 Cxx1yLoc = S->getLocStart();
986 return true;
987 }
988
989 ReturnStmts.push_back(S->getLocStart());
990 return true;
991
992 case Stmt::CompoundStmtClass: {
993 // C++1y allows compound-statements.
994 if (!Cxx1yLoc.isValid())
995 Cxx1yLoc = S->getLocStart();
996
997 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +0000998 for (auto *BodyIt : CompStmt->body()) {
999 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001000 Cxx1yLoc))
1001 return false;
1002 }
1003 return true;
1004 }
1005
1006 case Stmt::AttributedStmtClass:
1007 if (!Cxx1yLoc.isValid())
1008 Cxx1yLoc = S->getLocStart();
1009 return true;
1010
1011 case Stmt::IfStmtClass: {
1012 // C++1y allows if-statements.
1013 if (!Cxx1yLoc.isValid())
1014 Cxx1yLoc = S->getLocStart();
1015
1016 IfStmt *If = cast<IfStmt>(S);
1017 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1018 Cxx1yLoc))
1019 return false;
1020 if (If->getElse() &&
1021 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1022 Cxx1yLoc))
1023 return false;
1024 return true;
1025 }
1026
1027 case Stmt::WhileStmtClass:
1028 case Stmt::DoStmtClass:
1029 case Stmt::ForStmtClass:
1030 case Stmt::CXXForRangeStmtClass:
1031 case Stmt::ContinueStmtClass:
1032 // C++1y allows all of these. We don't allow them as extensions in C++11,
1033 // because they don't make sense without variable mutation.
1034 if (!SemaRef.getLangOpts().CPlusPlus1y)
1035 break;
1036 if (!Cxx1yLoc.isValid())
1037 Cxx1yLoc = S->getLocStart();
1038 for (Stmt::child_range Children = S->children(); Children; ++Children)
1039 if (*Children &&
1040 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1041 Cxx1yLoc))
1042 return false;
1043 return true;
1044
1045 case Stmt::SwitchStmtClass:
1046 case Stmt::CaseStmtClass:
1047 case Stmt::DefaultStmtClass:
1048 case Stmt::BreakStmtClass:
1049 // C++1y allows switch-statements, and since they don't need variable
1050 // mutation, we can reasonably allow them in C++11 as an extension.
1051 if (!Cxx1yLoc.isValid())
1052 Cxx1yLoc = S->getLocStart();
1053 for (Stmt::child_range Children = S->children(); Children; ++Children)
1054 if (*Children &&
1055 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1056 Cxx1yLoc))
1057 return false;
1058 return true;
1059
1060 default:
1061 if (!isa<Expr>(S))
1062 break;
1063
1064 // C++1y allows expression-statements.
1065 if (!Cxx1yLoc.isValid())
1066 Cxx1yLoc = S->getLocStart();
1067 return true;
1068 }
1069
1070 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1071 << isa<CXXConstructorDecl>(Dcl);
1072 return false;
1073}
1074
Richard Smitheb3c10c2011-10-01 02:31:28 +00001075/// Check the body for the given constexpr function declaration only contains
1076/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1077///
1078/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001079bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001080 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001081 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001082 // The definition of a constexpr function shall satisfy the following
1083 // constraints: [...]
1084 // - its function-body shall be = delete, = default, or a
1085 // compound-statement
1086 //
Richard Smith74388b42012-02-04 00:33:54 +00001087 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 // In the definition of a constexpr constructor, [...]
1089 // - its function-body shall not be a function-try-block;
1090 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1091 << isa<CXXConstructorDecl>(Dcl);
1092 return false;
1093 }
1094
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001095 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001096
1097 // - its function-body shall be [...] a compound-statement that contains only
1098 // [... list of cases ...]
1099 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1100 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001101 for (auto *BodyIt : CompBody->body()) {
1102 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001103 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 }
1105
Richard Smithd9f663b2013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smitheb3c10c2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001119 // DR1460:
1120 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001121 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001123 if (Constructor->getNumCtorInitializers() == 0 &&
1124 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001125 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1126 return false;
1127 }
Richard Smithf368fb42011-10-10 16:38:04 +00001128 } else if (!Constructor->isDependentContext() &&
1129 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1131
1132 // Skip detailed checking if we have enough initializers, and we would
1133 // allow at most one initializer per member.
1134 bool AnyAnonStructUnionMembers = false;
1135 unsigned Fields = 0;
1136 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1137 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001138 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001139 AnyAnonStructUnionMembers = true;
1140 break;
1141 }
1142 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001143 // DR1460:
1144 // - if the class is a union-like class, but is not a union, for each of
1145 // its anonymous union members having variant members, exactly one of
1146 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 if (AnyAnonStructUnionMembers ||
1148 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1149 // Check initialization of non-static data members. Base classes are
1150 // always initialized so do not need to be checked. Dependent bases
1151 // might not have initializers in the member initializer list.
1152 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001153 for (const auto *I: Constructor->inits()) {
1154 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001156 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001157 Inits.insert(ID->chain_begin(), ID->chain_end());
1158 }
1159
1160 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001161 for (auto *I : RD->fields())
1162 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 if (Diagnosed)
1164 return false;
1165 }
1166 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 } else {
1168 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001169 // C++1y doesn't require constexpr functions to contain a 'return'
1170 // statement. We still do, unless the return type is void, because
1171 // otherwise if there's no return statement, the function cannot
1172 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001173 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001174 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001175 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1176 : diag::err_constexpr_body_no_return);
1177 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001178 }
1179 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001180 Diag(ReturnStmts.back(),
1181 getLangOpts().CPlusPlus1y
1182 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1183 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1185 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 }
1187 }
1188
Richard Smith74388b42012-02-04 00:33:54 +00001189 // C++11 [dcl.constexpr]p5:
1190 // if no function argument values exist such that the function invocation
1191 // substitution would produce a constant expression, the program is
1192 // ill-formed; no diagnostic required.
1193 // C++11 [dcl.constexpr]p3:
1194 // - every constructor call and implicit conversion used in initializing the
1195 // return value shall be one of those allowed in a constant expression.
1196 // C++11 [dcl.constexpr]p4:
1197 // - every constructor involved in initializing non-static data members and
1198 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001199 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001200 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001201 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001202 << isa<CXXConstructorDecl>(Dcl);
1203 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1204 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001205 // Don't return false here: we allow this for compatibility in
1206 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001207 }
1208
Richard Smitheb3c10c2011-10-01 02:31:28 +00001209 return true;
1210}
1211
Douglas Gregor61956c42008-10-31 09:07:45 +00001212/// isCurrentClassName - Determine whether the identifier II is the
1213/// name of the class type currently being defined. In the case of
1214/// nested classes, this will only return true if II is the name of
1215/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001216bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1217 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001218 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001219
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001220 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001221 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001222 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1224 } else
1225 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1226
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001227 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001228 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001229 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001230}
1231
Richard Smithfb8b7b92013-10-15 00:00:26 +00001232/// \brief Determine whether the identifier II is a typo for the name of
1233/// the class type currently being defined. If so, update it to the identifier
1234/// that should have been used.
1235bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1236 assert(getLangOpts().CPlusPlus && "No class names in C!");
1237
1238 if (!getLangOpts().SpellChecking)
1239 return false;
1240
1241 CXXRecordDecl *CurDecl;
1242 if (SS && SS->isSet() && !SS->isInvalid()) {
1243 DeclContext *DC = computeDeclContext(*SS, true);
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1245 } else
1246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1247
1248 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1249 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1250 < II->getLength()) {
1251 II = CurDecl->getIdentifier();
1252 return true;
1253 }
1254
1255 return false;
1256}
1257
Douglas Gregordc974572012-11-10 07:24:09 +00001258/// \brief Determine whether the given class is a base class of the given
1259/// class, including looking at dependent bases.
1260static bool findCircularInheritance(const CXXRecordDecl *Class,
1261 const CXXRecordDecl *Current) {
1262 SmallVector<const CXXRecordDecl*, 8> Queue;
1263
1264 Class = Class->getCanonicalDecl();
1265 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001266 for (const auto &I : Current->bases()) {
1267 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001288}
1289
Mike Stump11289f42009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor463421d2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregor752a5952011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregor62004702012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump11289f42009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001341 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001362 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001363 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001364
Eli Friedmanc96d4962009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001372
David Majnemer9b1754d2013-11-02 12:00:36 +00001373 // A class which contains a flexible array member is not suitable for use as a
1374 // base class:
1375 // - If the layout determines that a base comes before another base,
1376 // the flexible array member would index into the subsequent base.
1377 // - If the layout determines that base comes before the derived class,
1378 // the flexible array member would index into the derived class.
1379 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
Anders Carlsson65c76d32011-03-25 14:55:14 +00001385 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001386 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001387 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001388 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001389 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001390 << CXXBaseDecl->getDeclName()
1391 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001392 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393 << CXXBaseDecl->getDeclName();
1394 return 0;
1395 }
1396
John McCall3696dcb2010-08-17 07:23:57 +00001397 if (BaseDecl->isInvalidDecl())
1398 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001399
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001400 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001404}
1405
Douglas Gregor556877c2008-04-13 21:30:24 +00001406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001408/// example:
1409/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001410/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001411BaseResult
John McCall48871652010-08-21 09:40:31 +00001412Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001413 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001414 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 ParsedType basetype, SourceLocation BaseLoc,
1416 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001417 if (!classdecl)
1418 return true;
1419
Douglas Gregorc40290e2009-03-09 23:48:35 +00001420 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001421 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001422 if (!Class)
1423 return true;
1424
Richard Smith4c96e992013-02-19 23:47:15 +00001425 // We do not support any C++11 attributes on base-specifiers yet.
1426 // Diagnose any attributes we see.
1427 if (!Attributes.empty()) {
1428 for (AttributeList *Attr = Attributes.getList(); Attr;
1429 Attr = Attr->getNext()) {
1430 if (Attr->isInvalid() ||
1431 Attr->getKind() == AttributeList::IgnoredAttribute)
1432 continue;
1433 Diag(Attr->getLoc(),
1434 Attr->getKind() == AttributeList::UnknownAttribute
1435 ? diag::warn_unknown_attribute_ignored
1436 : diag::err_base_specifier_attribute)
1437 << Attr->getName();
1438 }
1439 }
1440
Nick Lewycky19b9f952010-07-26 16:56:01 +00001441 TypeSourceInfo *TInfo = 0;
1442 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001443
Douglas Gregor752a5952011-01-03 22:36:02 +00001444 if (EllipsisLoc.isInvalid() &&
1445 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001446 UPPC_BaseType))
1447 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001448
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001450 Virtual, Access, TInfo,
1451 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001452 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001453 else
1454 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor463421d2009-03-03 04:44:36 +00001456 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001457}
Douglas Gregor556877c2008-04-13 21:30:24 +00001458
Douglas Gregor463421d2009-03-03 04:44:36 +00001459/// \brief Performs the actual work of attaching the given base class
1460/// specifiers to a C++ class.
1461bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462 unsigned NumBases) {
1463 if (NumBases == 0)
1464 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001465
1466 // Used to keep track of which base types we have already seen, so
1467 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001468 // that the key is always the unqualified canonical type of the base
1469 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001470 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471
1472 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001473 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001474 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001475 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001477 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001478 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001479
1480 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 // C++ [class.mi]p3:
1483 // A class shall not be specified as a direct base class of a
1484 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001485 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001486 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001487 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001488 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001489
1490 // Delete the duplicate base class specifier; we're going to
1491 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001492 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001493
1494 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001495 } else {
1496 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001497 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001498 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001499 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501 if (Class->isInterface() &&
1502 (!RD->isInterface() ||
1503 KnownBase->getAccessSpecifier() != AS_public)) {
1504 // The Microsoft extension __interface does not permit bases that
1505 // are not themselves public interfaces.
1506 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508 << RD->getSourceRange();
1509 Invalid = true;
1510 }
1511 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001512 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001513 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001514 }
1515 }
1516
1517 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001518 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001519
1520 // Delete the remaining (good) base class specifiers, since their
1521 // data has been copied into the CXXRecordDecl.
1522 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001523 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001524
1525 return Invalid;
1526}
1527
1528/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529/// class, after checking whether there are any duplicate base
1530/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001531void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 unsigned NumBases) {
1533 if (!ClassDecl || !Bases || !NumBases)
1534 return;
1535
1536 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001537 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001538}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001539
Douglas Gregor36d1b142009-10-06 17:59:45 +00001540/// \brief Determine whether the type \p Derived is a C++ class that is
1541/// derived from the type \p Base.
1542bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001543 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001544 return false;
John McCalle78aac42010-03-10 03:28:59 +00001545
Douglas Gregor45bb4832013-03-26 23:36:30 +00001546 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001547 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001548 return false;
1549
Douglas Gregor45bb4832013-03-26 23:36:30 +00001550 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001551 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001553
1554 // If either the base or the derived type is invalid, don't try to
1555 // check whether one is derived from the other.
1556 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557 return false;
1558
John McCall67da35c2010-02-04 22:26:26 +00001559 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1560 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001561}
1562
1563/// \brief Determine whether the type \p Derived is a C++ class that is
1564/// derived from the type \p Base.
1565bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001566 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001567 return false;
1568
Douglas Gregor45bb4832013-03-26 23:36:30 +00001569 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001570 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001571 return false;
1572
Douglas Gregor45bb4832013-03-26 23:36:30 +00001573 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001574 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor36d1b142009-10-06 17:59:45 +00001577 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578}
1579
Anders Carlssona70cff62010-04-24 19:06:50 +00001580void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001581 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001582 assert(BasePathArray.empty() && "Base path array must be empty!");
1583 assert(Paths.isRecordingPaths() && "Must record paths!");
1584
1585 const CXXBasePath &Path = Paths.front();
1586
1587 // We first go backward and check if we have a virtual base.
1588 // FIXME: It would be better if CXXBasePath had the base specifier for
1589 // the nearest virtual base.
1590 unsigned Start = 0;
1591 for (unsigned I = Path.size(); I != 0; --I) {
1592 if (Path[I - 1].Base->isVirtual()) {
1593 Start = I - 1;
1594 break;
1595 }
1596 }
1597
1598 // Now add all bases.
1599 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001600 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001601}
1602
Douglas Gregor88d292c2010-05-13 16:44:06 +00001603/// \brief Determine whether the given base path includes a virtual
1604/// base class.
John McCallcf142162010-08-07 06:22:56 +00001605bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606 for (CXXCastPath::const_iterator B = BasePath.begin(),
1607 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001608 B != BEnd; ++B)
1609 if ((*B)->isVirtual())
1610 return true;
1611
1612 return false;
1613}
1614
Douglas Gregor36d1b142009-10-06 17:59:45 +00001615/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616/// conversion (where Derived and Base are class types) is
1617/// well-formed, meaning that the conversion is unambiguous (and
1618/// that all of the base classes are accessible). Returns true
1619/// and emits a diagnostic if the code is ill-formed, returns false
1620/// otherwise. Loc is the location where this routine should point to
1621/// if there is an error, and Range is the source range to highlight
1622/// if there is an error.
1623bool
1624Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001625 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001626 unsigned AmbigiousBaseConvID,
1627 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001628 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001629 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001630 // First, determine whether the path from Derived to Base is
1631 // ambiguous. This is slightly more expensive than checking whether
1632 // the Derived to Base conversion exists, because here we need to
1633 // explore multiple paths to determine if there is an ambiguity.
1634 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635 /*DetectVirtual=*/false);
1636 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637 assert(DerivationOkay &&
1638 "Can only be used with a derived-to-base conversion");
1639 (void)DerivationOkay;
1640
1641 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001642 if (InaccessibleBaseID) {
1643 // Check that the base class can be accessed.
1644 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645 InaccessibleBaseID)) {
1646 case AR_inaccessible:
1647 return true;
1648 case AR_accessible:
1649 case AR_dependent:
1650 case AR_delayed:
1651 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001652 }
John McCall5b0829a2010-02-10 09:31:12 +00001653 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001654
1655 // Build a base path if necessary.
1656 if (BasePath)
1657 BuildBasePathArray(Paths, *BasePath);
1658 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001659 }
1660
David Majnemer626032f2013-06-22 06:43:58 +00001661 if (AmbigiousBaseConvID) {
1662 // We know that the derived-to-base conversion is ambiguous, and
1663 // we're going to produce a diagnostic. Perform the derived-to-base
1664 // search just one more time to compute all of the possible paths so
1665 // that we can print them out. This is more expensive than any of
1666 // the previous derived-to-base checks we've done, but at this point
1667 // performance isn't as much of an issue.
1668 Paths.clear();
1669 Paths.setRecordingPaths(true);
1670 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672 (void)StillOkay;
1673
1674 // Build up a textual representation of the ambiguous paths, e.g.,
1675 // D -> B -> A, that will be used to illustrate the ambiguous
1676 // conversions in the diagnostic. We only print one of the paths
1677 // to each base class subobject.
1678 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679
1680 Diag(Loc, AmbigiousBaseConvID)
1681 << Derived << Base << PathDisplayStr << Range << Name;
1682 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001683 return true;
1684}
1685
1686bool
1687Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001688 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001689 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001690 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001692 IgnoreAccess ? 0
1693 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001695 Loc, Range, DeclarationName(),
1696 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697}
1698
1699
1700/// @brief Builds a string representing ambiguous paths from a
1701/// specific derived class to different subobjects of the same base
1702/// class.
1703///
1704/// This function builds a string that can be used in error messages
1705/// to show the different paths that one can take through the
1706/// inheritance hierarchy to go from the derived class to different
1707/// subobjects of a base class. The result looks something like this:
1708/// @code
1709/// struct D -> struct B -> struct A
1710/// struct D -> struct C -> struct A
1711/// @endcode
1712std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713 std::string PathDisplayStr;
1714 std::set<unsigned> DisplayedPaths;
1715 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716 Path != Paths.end(); ++Path) {
1717 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718 // We haven't displayed a path to this particular base
1719 // class subobject yet.
1720 PathDisplayStr += "\n ";
1721 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722 for (CXXBasePath::const_iterator Element = Path->begin();
1723 Element != Path->end(); ++Element)
1724 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725 }
1726 }
1727
1728 return PathDisplayStr;
1729}
1730
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001731//===----------------------------------------------------------------------===//
1732// C++ class member Handling
1733//===----------------------------------------------------------------------===//
1734
Abramo Bagnarad7340582010-06-05 05:09:32 +00001735/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001736bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737 SourceLocation ASLoc,
1738 SourceLocation ColonLoc,
1739 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001740 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001741 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001742 ASLoc, ColonLoc);
1743 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001744 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745}
1746
Richard Smith18f07db2012-08-06 03:25:17 +00001747/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001748void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001749 if (D->isInvalidDecl())
1750 return;
1751
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001752 // We only care about "override" and "final" declarations.
1753 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001755
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001756 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001757
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001758 // We can't check dependent instance methods.
1759 if (MD && MD->isInstance() &&
1760 (MD->getParent()->hasAnyDependentBases() ||
1761 MD->getType()->isDependentType()))
1762 return;
1763
1764 if (MD && !MD->isVirtual()) {
1765 // If we have a non-virtual method, check if if hides a virtual method.
1766 // (In that case, it's most likely the method has the wrong type.)
1767 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768 FindHiddenVirtualMethods(MD, OverloadedMethods);
1769
1770 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001771 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001773 diag::override_keyword_hides_virtual_member_function)
1774 << "override" << (OverloadedMethods.size() > 1);
1775 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001776 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001777 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001778 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001780 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001781 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782 MD->setInvalidDecl();
1783 return;
1784 }
1785 // Fall through into the general case diagnostic.
1786 // FIXME: We might want to attempt typo correction here.
1787 }
1788
1789 if (!MD || !MD->isVirtual()) {
1790 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791 Diag(OA->getLocation(),
1792 diag::override_keyword_only_allowed_on_virtual_member_functions)
1793 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794 D->dropAttr<OverrideAttr>();
1795 }
1796 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797 Diag(FA->getLocation(),
1798 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001799 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001801 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001802 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001803 return;
1804 }
Richard Smith18f07db2012-08-06 03:25:17 +00001805
Richard Smith18f07db2012-08-06 03:25:17 +00001806 // C++11 [class.virtual]p5:
1807 // If a virtual function is marked with the virt-specifier override and
1808 // does not override a member function of a base class, the program is
1809 // ill-formed.
1810 bool HasOverriddenMethods =
1811 MD->begin_overridden_methods() != MD->end_overridden_methods();
1812 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001815}
1816
Richard Smith18f07db2012-08-06 03:25:17 +00001817/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001818/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001819/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001820bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001822 FinalAttr *FA = Old->getAttr<FinalAttr>();
1823 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001824 return false;
1825
1826 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001827 << New->getDeclName()
1828 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001831}
1832
Daniel Jasper0baec5492012-06-06 08:32:04 +00001833static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001834 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835 // FIXME: Destruction of ObjC lifetime types has side-effects.
1836 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837 return !RD->isCompleteDefinition() ||
1838 !RD->hasTrivialDefaultConstructor() ||
1839 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001840 return false;
1841}
1842
John McCall5e77d762013-04-16 07:28:30 +00001843static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844 for (AttributeList* it = list; it != 0; it = it->getNext())
1845 if (it->isDeclspecPropertyAttribute())
1846 return it;
1847 return 0;
1848}
1849
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001850/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001852/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001853/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001855NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001856Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001857 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001858 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001859 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001860 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001861 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862 DeclarationName Name = NameInfo.getName();
1863 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001864
1865 // For anonymous bitfields, the location should point to the type.
1866 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001867 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001868
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001869 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870
John McCallb1cd7da2010-06-04 08:34:12 +00001871 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001872 assert(!DS.isFriendSpecified());
1873
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001874 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001875
John McCalldb632ac2012-09-25 07:32:39 +00001876 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877 // The Microsoft extension __interface only permits public member functions
1878 // and prohibits constructors, destructors, operators, non-public member
1879 // functions, static methods and data members.
1880 unsigned InvalidDecl;
1881 bool ShowDeclName = true;
1882 if (!isFunc)
1883 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884 else if (AS != AS_public)
1885 InvalidDecl = 2;
1886 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887 InvalidDecl = 3;
1888 else switch (Name.getNameKind()) {
1889 case DeclarationName::CXXConstructorName:
1890 InvalidDecl = 4;
1891 ShowDeclName = false;
1892 break;
1893
1894 case DeclarationName::CXXDestructorName:
1895 InvalidDecl = 5;
1896 ShowDeclName = false;
1897 break;
1898
1899 case DeclarationName::CXXOperatorName:
1900 case DeclarationName::CXXConversionFunctionName:
1901 InvalidDecl = 6;
1902 break;
1903
1904 default:
1905 InvalidDecl = 0;
1906 break;
1907 }
1908
1909 if (InvalidDecl) {
1910 if (ShowDeclName)
1911 Diag(Loc, diag::err_invalid_member_in_interface)
1912 << (InvalidDecl-1) << Name;
1913 else
1914 Diag(Loc, diag::err_invalid_member_in_interface)
1915 << (InvalidDecl-1) << "";
1916 return 0;
1917 }
1918 }
1919
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001920 // C++ 9.2p6: A member shall not be declared to have automatic storage
1921 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001922 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923 // data members and cannot be applied to names declared const or static,
1924 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001926 case DeclSpec::SCS_unspecified:
1927 case DeclSpec::SCS_typedef:
1928 case DeclSpec::SCS_static:
1929 break;
1930 case DeclSpec::SCS_mutable:
1931 if (isFunc) {
1932 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Richard Smithb4a9e862013-04-12 22:46:28 +00001934 // FIXME: It would be nicer if the keyword was ignored only for this
1935 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001937 }
1938 break;
1939 default:
1940 Diag(DS.getStorageClassSpecLoc(),
1941 diag::err_storageclass_invalid_for_member);
1942 D.getMutableDeclSpec().ClearStorageClassSpecs();
1943 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944 }
1945
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001946 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001948 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001949
David Blaikie35506f82013-01-30 01:22:18 +00001950 if (DS.isConstexprSpecified() && isInstField) {
1951 SemaDiagnosticBuilder B =
1952 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954 if (InitStyle == ICIS_NoInit) {
1955 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956 D.getMutableDeclSpec().ClearConstexprSpec();
1957 const char *PrevSpec;
1958 unsigned DiagID;
1959 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001961 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001962 assert(!Failed && "Making a constexpr member const shouldn't fail");
1963 } else {
1964 B << 1;
1965 const char *PrevSpec;
1966 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001967 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001968 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1969 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001970 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001971 "This is the only DeclSpec that should fail to be applied");
1972 B << 1;
1973 } else {
1974 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1975 isInstField = false;
1976 }
1977 }
1978 }
1979
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001980 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001981 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001982 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001983
1984 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001985 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001986 Diag(Loc, diag::err_bad_variable_name)
1987 << Name;
1988 return 0;
1989 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001990
Benjamin Kramer365082d2012-05-19 16:34:46 +00001991 IdentifierInfo *II = Name.getAsIdentifierInfo();
1992
Douglas Gregor7c26c042011-09-21 14:40:46 +00001993 // Member field could not be with "template" keyword.
1994 // So TemplateParameterLists should be empty in this case.
1995 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001996 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00001997 if (TemplateParams->size()) {
1998 // There is no such thing as a member field template.
1999 Diag(D.getIdentifierLoc(), diag::err_template_member)
2000 << II
2001 << SourceRange(TemplateParams->getTemplateLoc(),
2002 TemplateParams->getRAngleLoc());
2003 } else {
2004 // There is an extraneous 'template<>' for this member.
2005 Diag(TemplateParams->getTemplateLoc(),
2006 diag::err_template_member_noparams)
2007 << II
2008 << SourceRange(TemplateParams->getTemplateLoc(),
2009 TemplateParams->getRAngleLoc());
2010 }
2011 return 0;
2012 }
2013
Douglas Gregora007d362010-10-13 22:19:53 +00002014 if (SS.isSet() && !SS.isInvalid()) {
2015 // The user provided a superfluous scope specifier inside a class
2016 // definition:
2017 //
2018 // class X {
2019 // int X::member;
2020 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002021 if (DeclContext *DC = computeDeclContext(SS, false))
2022 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002023 else
2024 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2025 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002026
Douglas Gregora007d362010-10-13 22:19:53 +00002027 SS.clear();
2028 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002029
John McCall5e77d762013-04-16 07:28:30 +00002030 AttributeList *MSPropertyAttr =
2031 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002032 if (MSPropertyAttr) {
2033 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2034 BitWidth, InitStyle, AS, MSPropertyAttr);
2035 if (!Member)
2036 return 0;
2037 isInstField = false;
2038 } else {
2039 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2040 BitWidth, InitStyle, AS);
2041 assert(Member && "HandleField never returns null");
2042 }
2043 } else {
2044 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2045
2046 Member = HandleDeclarator(S, D, TemplateParameterLists);
2047 if (!Member)
2048 return 0;
2049
2050 // Non-instance-fields can't have a bitfield.
2051 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002052 if (Member->isInvalidDecl()) {
2053 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002054 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002055 // C++ 9.6p3: A bit-field shall not be a static member.
2056 // "static member 'A' cannot be a bit-field"
2057 Diag(Loc, diag::err_static_not_bitfield)
2058 << Name << BitWidth->getSourceRange();
2059 } else if (isa<TypedefDecl>(Member)) {
2060 // "typedef member 'x' cannot be a bit-field"
2061 Diag(Loc, diag::err_typedef_not_bitfield)
2062 << Name << BitWidth->getSourceRange();
2063 } else {
2064 // A function typedef ("typedef int f(); f a;").
2065 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2066 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002067 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002068 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Chris Lattnerd26760a2009-03-05 23:01:03 +00002071 BitWidth = 0;
2072 Member->setInvalidDecl();
2073 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002074
2075 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002076
Larisse Voufo39a1e502013-08-06 01:03:05 +00002077 // If we have declared a member function template or static data member
2078 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002079 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2080 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002081 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2082 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002083 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002084
Richard Smith18f07db2012-08-06 03:25:17 +00002085 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002086 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002087 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002088 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2089 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002090
Douglas Gregorf2f08062011-03-08 17:10:18 +00002091 if (VS.getLastLocation().isValid()) {
2092 // Update the end location of a method that has a virt-specifiers.
2093 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2094 MD->setRangeEnd(VS.getLastLocation());
2095 }
Richard Smith18f07db2012-08-06 03:25:17 +00002096
Anders Carlssonc87f8612011-01-20 06:29:02 +00002097 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002098
Douglas Gregor92751d42008-11-17 22:58:34 +00002099 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002100
Daniel Jasper0baec5492012-06-06 08:32:04 +00002101 if (isInstField) {
2102 FieldDecl *FD = cast<FieldDecl>(Member);
2103 FieldCollector->Add(FD);
2104
2105 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2106 FD->getLocation())
2107 != DiagnosticsEngine::Ignored) {
2108 // Remember all explicit private FieldDecls that have a name, no side
2109 // effects and are not part of a dependent type declaration.
2110 if (!FD->isImplicit() && FD->getDeclName() &&
2111 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002112 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002113 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002114 !InitializationHasSideEffects(*FD))
2115 UnusedPrivateFields.insert(FD);
2116 }
2117 }
2118
John McCall48871652010-08-21 09:40:31 +00002119 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002120}
2121
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002122namespace {
2123 class UninitializedFieldVisitor
2124 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2125 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002126 // List of Decls to generate a warning on. Also remove Decls that become
2127 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002128 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002129 // If non-null, add a note to the warning pointing back to the constructor.
2130 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002131 public:
2132 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002133 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002134 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002135 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002136 : Inherited(S.Context), S(S), Decls(Decls),
2137 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002138
Richard Trieufd687772013-09-16 20:46:50 +00002139 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002140 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2141 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002142
Richard Trieu1bc22c12013-09-13 03:20:53 +00002143 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2144 // or union.
2145 MemberExpr *FieldME = ME;
2146
2147 Expr *Base = ME;
2148 while (isa<MemberExpr>(Base)) {
2149 ME = cast<MemberExpr>(Base);
2150
2151 if (isa<VarDecl>(ME->getMemberDecl()))
2152 return;
2153
2154 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2155 if (!FD->isAnonymousStructOrUnion())
2156 FieldME = ME;
2157
2158 Base = ME->getBase();
2159 }
2160
Richard Trieufd687772013-09-16 20:46:50 +00002161 if (!isa<CXXThisExpr>(Base))
2162 return;
2163
Richard Trieu406e65c2013-09-20 03:03:06 +00002164 ValueDecl* FoundVD = FieldME->getMemberDecl();
2165
Richard Trieuef64e942013-10-25 00:56:00 +00002166 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002167 return;
2168
Richard Trieuef64e942013-10-25 00:56:00 +00002169 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002170
Richard Trieuef64e942013-10-25 00:56:00 +00002171 // Prevent double warnings on use of unbounded references.
2172 if (IsReference != CheckReferenceOnly)
2173 return;
2174
2175 unsigned diag = IsReference
2176 ? diag::warn_reference_field_is_uninit
2177 : diag::warn_field_is_uninit;
2178 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2179 if (Constructor)
2180 S.Diag(Constructor->getLocation(),
2181 diag::note_uninit_in_this_constructor)
2182 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2183
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002184 }
2185
2186 void HandleValue(Expr *E) {
2187 E = E->IgnoreParens();
2188
2189 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002190 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002191 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002192 }
2193
2194 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2195 HandleValue(CO->getTrueExpr());
2196 HandleValue(CO->getFalseExpr());
2197 return;
2198 }
2199
2200 if (BinaryConditionalOperator *BCO =
2201 dyn_cast<BinaryConditionalOperator>(E)) {
2202 HandleValue(BCO->getCommon());
2203 HandleValue(BCO->getFalseExpr());
2204 return;
2205 }
2206
2207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2208 switch (BO->getOpcode()) {
2209 default:
2210 return;
2211 case(BO_PtrMemD):
2212 case(BO_PtrMemI):
2213 HandleValue(BO->getLHS());
2214 return;
2215 case(BO_Comma):
2216 HandleValue(BO->getRHS());
2217 return;
2218 }
2219 }
2220 }
2221
Richard Trieu1bc22c12013-09-13 03:20:53 +00002222 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002223 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002224 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002225
2226 Inherited::VisitMemberExpr(ME);
2227 }
2228
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002229 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2230 if (E->getCastKind() == CK_LValueToRValue)
2231 HandleValue(E->getSubExpr());
2232
2233 Inherited::VisitImplicitCastExpr(E);
2234 }
2235
Richard Trieu1bc22c12013-09-13 03:20:53 +00002236 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002237 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002238 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2239 if (ICE->getCastKind() == CK_NoOp)
2240 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002241 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002242
2243 Inherited::VisitCXXConstructExpr(E);
2244 }
2245
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002246 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2247 Expr *Callee = E->getCallee();
2248 if (isa<MemberExpr>(Callee))
2249 HandleValue(Callee);
2250
2251 Inherited::VisitCXXMemberCallExpr(E);
2252 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002253
2254 void VisitBinaryOperator(BinaryOperator *E) {
2255 // If a field assignment is detected, remove the field from the
2256 // uninitiailized field set.
2257 if (E->getOpcode() == BO_Assign)
2258 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2259 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002260 if (!FD->getType()->isReferenceType())
2261 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002262
2263 Inherited::VisitBinaryOperator(E);
2264 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002265 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002266 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002267 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2268 const CXXConstructorDecl *Constructor) {
2269 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002270 return;
2271
Richard Trieuef64e942013-10-25 00:56:00 +00002272 if (!E)
2273 return;
2274
2275 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2276 E = Default->getExpr();
2277 if (!E)
2278 return;
2279 // In class initializers will point to the constructor.
2280 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2281 } else {
2282 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2283 }
2284 }
2285
2286 // Diagnose value-uses of fields to initialize themselves, e.g.
2287 // foo(foo)
2288 // where foo is not also a parameter to the constructor.
2289 // Also diagnose across field uninitialized use such as
2290 // x(y), y(x)
2291 // TODO: implement -Wuninitialized and fold this into that framework.
2292 static void DiagnoseUninitializedFields(
2293 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2294
2295 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2296 Constructor->getLocation())
2297 == DiagnosticsEngine::Ignored) {
2298 return;
2299 }
2300
2301 if (Constructor->isInvalidDecl())
2302 return;
2303
2304 const CXXRecordDecl *RD = Constructor->getParent();
2305
2306 // Holds fields that are uninitialized.
2307 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2308
2309 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002310 for (auto *I : RD->decls()) {
2311 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002312 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002313 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002314 UninitializedFields.insert(IFD->getAnonField());
2315 }
2316 }
2317
Aaron Ballman0ad78302014-03-13 17:34:31 +00002318 for (const auto *FieldInit : Constructor->inits()) {
2319 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002320
2321 CheckInitExprContainsUninitializedFields(
2322 SemaRef, InitExpr, UninitializedFields, Constructor);
2323
Aaron Ballman0ad78302014-03-13 17:34:31 +00002324 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002325 UninitializedFields.erase(Field);
2326 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002327 }
2328} // namespace
2329
Richard Smith74108172014-01-17 03:11:34 +00002330/// \brief Enter a new C++ default initializer scope. After calling this, the
2331/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2332/// parsing or instantiating the initializer failed.
2333void Sema::ActOnStartCXXInClassMemberInitializer() {
2334 // Create a synthetic function scope to represent the call to the constructor
2335 // that notionally surrounds a use of this initializer.
2336 PushFunctionScope();
2337}
2338
2339/// \brief This is invoked after parsing an in-class initializer for a
2340/// non-static C++ class member, and after instantiating an in-class initializer
2341/// in a class template. Such actions are deferred until the class is complete.
2342void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2343 SourceLocation InitLoc,
2344 Expr *InitExpr) {
2345 // Pop the notional constructor scope we created earlier.
2346 PopFunctionScopeInfo(0, D);
2347
Richard Smith938f40b2011-06-11 17:19:42 +00002348 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002349 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2350 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002351
2352 if (!InitExpr) {
2353 FD->setInvalidDecl();
2354 FD->removeInClassInitializer();
2355 return;
2356 }
2357
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002358 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2359 FD->setInvalidDecl();
2360 FD->removeInClassInitializer();
2361 return;
2362 }
2363
Richard Smith938f40b2011-06-11 17:19:42 +00002364 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002365 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002366 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002367 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002368 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002369 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002370 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2371 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002372 if (Init.isInvalid()) {
2373 FD->setInvalidDecl();
2374 return;
2375 }
Richard Smith938f40b2011-06-11 17:19:42 +00002376 }
2377
Richard Smith945f8d32013-01-14 22:39:08 +00002378 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002379 // The initialization of each base and member constitutes a
2380 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002381 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002382 if (Init.isInvalid()) {
2383 FD->setInvalidDecl();
2384 return;
2385 }
2386
2387 InitExpr = Init.release();
2388
2389 FD->setInClassInitializer(InitExpr);
2390}
2391
Douglas Gregor15e77a22009-12-31 09:10:24 +00002392/// \brief Find the direct and/or virtual base specifiers that
2393/// correspond to the given base type, for use in base initialization
2394/// within a constructor.
2395static bool FindBaseInitializer(Sema &SemaRef,
2396 CXXRecordDecl *ClassDecl,
2397 QualType BaseType,
2398 const CXXBaseSpecifier *&DirectBaseSpec,
2399 const CXXBaseSpecifier *&VirtualBaseSpec) {
2400 // First, check for a direct base class.
2401 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002402 for (const auto &Base : ClassDecl->bases()) {
2403 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002404 // We found a direct base of this type. That's what we're
2405 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002406 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002407 break;
2408 }
2409 }
2410
2411 // Check for a virtual base class.
2412 // FIXME: We might be able to short-circuit this if we know in advance that
2413 // there are no virtual bases.
2414 VirtualBaseSpec = 0;
2415 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2416 // We haven't found a base yet; search the class hierarchy for a
2417 // virtual base class.
2418 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2419 /*DetectVirtual=*/false);
2420 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2421 BaseType, Paths)) {
2422 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2423 Path != Paths.end(); ++Path) {
2424 if (Path->back().Base->isVirtual()) {
2425 VirtualBaseSpec = Path->back().Base;
2426 break;
2427 }
2428 }
2429 }
2430 }
2431
2432 return DirectBaseSpec || VirtualBaseSpec;
2433}
2434
Sebastian Redla74948d2011-09-24 17:48:25 +00002435/// \brief Handle a C++ member initializer using braced-init-list syntax.
2436MemInitResult
2437Sema::ActOnMemInitializer(Decl *ConstructorD,
2438 Scope *S,
2439 CXXScopeSpec &SS,
2440 IdentifierInfo *MemberOrBase,
2441 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002442 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002443 SourceLocation IdLoc,
2444 Expr *InitList,
2445 SourceLocation EllipsisLoc) {
2446 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002447 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002448 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002449}
2450
2451/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002452MemInitResult
John McCall48871652010-08-21 09:40:31 +00002453Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002454 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002455 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002456 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002457 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002458 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002459 SourceLocation IdLoc,
2460 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002461 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002462 SourceLocation RParenLoc,
2463 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002464 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002465 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002466 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002467 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002468}
2469
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002470namespace {
2471
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002472// Callback to only accept typo corrections that can be a valid C++ member
2473// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002474class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002475public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002476 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2477 : ClassDecl(ClassDecl) {}
2478
Craig Toppera798a9d2014-03-02 09:32:10 +00002479 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002480 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2481 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2482 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002483 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002484 }
2485 return false;
2486 }
2487
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002488private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489 CXXRecordDecl *ClassDecl;
2490};
2491
2492}
2493
Sebastian Redla74948d2011-09-24 17:48:25 +00002494/// \brief Handle a C++ member initializer.
2495MemInitResult
2496Sema::BuildMemInitializer(Decl *ConstructorD,
2497 Scope *S,
2498 CXXScopeSpec &SS,
2499 IdentifierInfo *MemberOrBase,
2500 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002501 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002502 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002503 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002504 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002505 if (!ConstructorD)
2506 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002507
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002508 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002509
2510 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002511 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002512 if (!Constructor) {
2513 // The user wrote a constructor initializer on a function that is
2514 // not a C++ constructor. Ignore the error for now, because we may
2515 // have more member initializers coming; we'll diagnose it just
2516 // once in ActOnMemInitializers.
2517 return true;
2518 }
2519
2520 CXXRecordDecl *ClassDecl = Constructor->getParent();
2521
2522 // C++ [class.base.init]p2:
2523 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002524 // constructor's class and, if not found in that scope, are looked
2525 // up in the scope containing the constructor's definition.
2526 // [Note: if the constructor's class contains a member with the
2527 // same name as a direct or virtual base class of the class, a
2528 // mem-initializer-id naming the member or base class and composed
2529 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002530 // mem-initializer-id for the hidden base class may be specified
2531 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002532 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002533 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002534 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002535 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002536 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002537 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002538 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2539 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002540 if (EllipsisLoc.isValid())
2541 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002542 << MemberOrBase
2543 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002544
Sebastian Redla9351792012-02-11 23:51:47 +00002545 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002546 }
Francois Pichetd583da02010-12-04 09:14:42 +00002547 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002548 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002549 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002550 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002551 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002552
2553 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002554 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002555 } else if (DS.getTypeSpecType() == TST_decltype) {
2556 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002557 } else {
2558 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2559 LookupParsedName(R, S, &SS);
2560
2561 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2562 if (!TyD) {
2563 if (R.isAmbiguous()) return true;
2564
John McCallda6841b2010-04-09 19:01:14 +00002565 // We don't want access-control diagnostics here.
2566 R.suppressDiagnostics();
2567
Douglas Gregora3b624a2010-01-19 06:46:48 +00002568 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2569 bool NotUnknownSpecialization = false;
2570 DeclContext *DC = computeDeclContext(SS, false);
2571 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2572 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2573
2574 if (!NotUnknownSpecialization) {
2575 // When the scope specifier can refer to a member of an unknown
2576 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002577 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2578 SS.getWithLocInContext(Context),
2579 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002580 if (BaseType.isNull())
2581 return true;
2582
Douglas Gregora3b624a2010-01-19 06:46:48 +00002583 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002584 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002585 }
2586 }
2587
Douglas Gregor15e77a22009-12-31 09:10:24 +00002588 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002589 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002590 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002591 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002592 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002593 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002594 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002595 // We have found a non-static data member with a similar
2596 // name to what was typed; complain and initialize that
2597 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002598 diagnoseTypo(Corr,
2599 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2600 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002601 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002602 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002603 const CXXBaseSpecifier *DirectBaseSpec;
2604 const CXXBaseSpecifier *VirtualBaseSpec;
2605 if (FindBaseInitializer(*this, ClassDecl,
2606 Context.getTypeDeclType(Type),
2607 DirectBaseSpec, VirtualBaseSpec)) {
2608 // We have found a direct or virtual base class with a
2609 // similar name to what was typed; complain and initialize
2610 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002611 diagnoseTypo(Corr,
2612 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2613 << MemberOrBase << false,
2614 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002615
Richard Smithf9b15102013-08-17 00:46:16 +00002616 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2617 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002618 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002619 diag::note_base_class_specified_here)
2620 << BaseSpec->getType()
2621 << BaseSpec->getSourceRange();
2622
Douglas Gregor15e77a22009-12-31 09:10:24 +00002623 TyD = Type;
2624 }
2625 }
2626 }
2627
Douglas Gregora3b624a2010-01-19 06:46:48 +00002628 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002629 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002630 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002631 return true;
2632 }
John McCallb5a0d312009-12-21 10:41:20 +00002633 }
2634
Douglas Gregora3b624a2010-01-19 06:46:48 +00002635 if (BaseType.isNull()) {
2636 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002637 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002638 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002639 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2640 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002641 }
2642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643
John McCallbcd03502009-12-07 02:54:59 +00002644 if (!TInfo)
2645 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002646
Sebastian Redla9351792012-02-11 23:51:47 +00002647 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002648}
2649
Chandler Carruth599deef2011-09-03 01:14:15 +00002650/// Checks a member initializer expression for cases where reference (or
2651/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002652static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2653 Expr *Init,
2654 SourceLocation IdLoc) {
2655 QualType MemberTy = Member->getType();
2656
2657 // We only handle pointers and references currently.
2658 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2659 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2660 return;
2661
2662 const bool IsPointer = MemberTy->isPointerType();
2663 if (IsPointer) {
2664 if (const UnaryOperator *Op
2665 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2666 // The only case we're worried about with pointers requires taking the
2667 // address.
2668 if (Op->getOpcode() != UO_AddrOf)
2669 return;
2670
2671 Init = Op->getSubExpr();
2672 } else {
2673 // We only handle address-of expression initializers for pointers.
2674 return;
2675 }
2676 }
2677
Richard Smithe3b28bc2013-06-12 21:51:50 +00002678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002679 // We only warn when referring to a non-reference parameter declaration.
2680 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2681 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002682 return;
2683
2684 S.Diag(Init->getExprLoc(),
2685 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2686 : diag::warn_bind_ref_member_to_parameter)
2687 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002688 } else {
2689 // Other initializers are fine.
2690 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002691 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002692
2693 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2694 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002695}
2696
John McCallfaf5fb42010-08-26 23:41:50 +00002697MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002698Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002699 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002700 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2701 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2702 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002703 "Member must be a FieldDecl or IndirectFieldDecl");
2704
Sebastian Redla9351792012-02-11 23:51:47 +00002705 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002706 return true;
2707
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002708 if (Member->isInvalidDecl())
2709 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002710
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002711 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002712 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002713 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002714 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002715 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002716 } else {
2717 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002718 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002719 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002720
Sebastian Redla9351792012-02-11 23:51:47 +00002721 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002722
Sebastian Redla9351792012-02-11 23:51:47 +00002723 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002724 // Can't check initialization for a member of dependent type or when
2725 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002726 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002727 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002728 bool InitList = false;
2729 if (isa<InitListExpr>(Init)) {
2730 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002731 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002732 }
2733
Chandler Carruthd44c3102010-12-06 09:23:57 +00002734 // Initialize the member.
2735 InitializedEntity MemberEntity =
2736 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2737 : InitializedEntity::InitializeMember(IndirectMember, 0);
2738 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002739 InitList ? InitializationKind::CreateDirectList(IdLoc)
2740 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2741 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002742
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002743 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2744 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002745 if (MemberInit.isInvalid())
2746 return true;
2747
Richard Smith736a9472013-06-12 20:42:33 +00002748 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2749
Richard Smith945f8d32013-01-14 22:39:08 +00002750 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002751 // The initialization of each base and member constitutes a
2752 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002753 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002754 if (MemberInit.isInvalid())
2755 return true;
2756
Richard Smithd59b8322012-12-19 01:39:02 +00002757 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002758 }
2759
Chandler Carruthd44c3102010-12-06 09:23:57 +00002760 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002761 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2762 InitRange.getBegin(), Init,
2763 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002764 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002765 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2766 InitRange.getBegin(), Init,
2767 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002768 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002769}
2770
John McCallfaf5fb42010-08-26 23:41:50 +00002771MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002772Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002773 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002774 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002775 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002776 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002777 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002778 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002779
Sebastian Redl0501c632012-02-12 16:37:36 +00002780 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002781 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002782 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2783 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002784 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002785 }
2786
Sebastian Redla9351792012-02-11 23:51:47 +00002787 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002788 // Initialize the object.
2789 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2790 QualType(ClassDecl->getTypeForDecl(), 0));
2791 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002792 InitList ? InitializationKind::CreateDirectList(NameLoc)
2793 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2794 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002795 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002796 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002797 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002798 if (DelegationInit.isInvalid())
2799 return true;
2800
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002801 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2802 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803
Richard Smith945f8d32013-01-14 22:39:08 +00002804 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002805 // The initialization of each base and member constitutes a
2806 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002807 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2808 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002809 if (DelegationInit.isInvalid())
2810 return true;
2811
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002812 // If we are in a dependent context, template instantiation will
2813 // perform this type-checking again. Just save the arguments that we
2814 // received in a ParenListExpr.
2815 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2816 // of the information that we have about the base
2817 // initializer. However, deconstructing the ASTs is a dicey process,
2818 // and this approach is far more likely to get the corner cases right.
2819 if (CurContext->isDependentContext())
2820 DelegationInit = Owned(Init);
2821
Sebastian Redla9351792012-02-11 23:51:47 +00002822 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002823 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002824 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002825}
2826
2827MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002828Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002829 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002830 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002831 SourceLocation BaseLoc
2832 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002833
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002834 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2835 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2836 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2837
2838 // C++ [class.base.init]p2:
2839 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002840 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002841 // of that class, the mem-initializer is ill-formed. A
2842 // mem-initializer-list can initialize a base class using any
2843 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002844 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002845
Sebastian Redla9351792012-02-11 23:51:47 +00002846 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002847 if (EllipsisLoc.isValid()) {
2848 // This is a pack expansion.
2849 if (!BaseType->containsUnexpandedParameterPack()) {
2850 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002851 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002852
Douglas Gregor44e7df62011-01-04 00:32:56 +00002853 EllipsisLoc = SourceLocation();
2854 }
2855 } else {
2856 // Check for any unexpanded parameter packs.
2857 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2858 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002859
Sebastian Redla9351792012-02-11 23:51:47 +00002860 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002861 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002863
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002864 // Check for direct and virtual base classes.
2865 const CXXBaseSpecifier *DirectBaseSpec = 0;
2866 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2867 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002868 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2869 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002870 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002871
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002872 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2873 VirtualBaseSpec);
2874
2875 // C++ [base.class.init]p2:
2876 // Unless the mem-initializer-id names a nonstatic data member of the
2877 // constructor's class or a direct or virtual base of that class, the
2878 // mem-initializer is ill-formed.
2879 if (!DirectBaseSpec && !VirtualBaseSpec) {
2880 // If the class has any dependent bases, then it's possible that
2881 // one of those types will resolve to the same type as
2882 // BaseType. Therefore, just treat this as a dependent base
2883 // class initialization. FIXME: Should we try to check the
2884 // initialization anyway? It seems odd.
2885 if (ClassDecl->hasAnyDependentBases())
2886 Dependent = true;
2887 else
2888 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2889 << BaseType << Context.getTypeDeclType(ClassDecl)
2890 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2891 }
2892 }
2893
2894 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002895 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002896
Sebastian Redla74948d2011-09-24 17:48:25 +00002897 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2898 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002899 InitRange.getBegin(), Init,
2900 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002901 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002902
2903 // C++ [base.class.init]p2:
2904 // If a mem-initializer-id is ambiguous because it designates both
2905 // a direct non-virtual base class and an inherited virtual base
2906 // class, the mem-initializer is ill-formed.
2907 if (DirectBaseSpec && VirtualBaseSpec)
2908 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002909 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002910
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002911 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002912 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002913 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002914
2915 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002916 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002917 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002918 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002919 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002920 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002921 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002922
2923 InitializedEntity BaseEntity =
2924 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2925 InitializationKind Kind =
2926 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2927 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2928 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002929 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2930 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002931 if (BaseInit.isInvalid())
2932 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002933
Richard Smith945f8d32013-01-14 22:39:08 +00002934 // C++11 [class.base.init]p7:
2935 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002936 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002937 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002938 if (BaseInit.isInvalid())
2939 return true;
2940
2941 // If we are in a dependent context, template instantiation will
2942 // perform this type-checking again. Just save the arguments that we
2943 // received in a ParenListExpr.
2944 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2945 // of the information that we have about the base
2946 // initializer. However, deconstructing the ASTs is a dicey process,
2947 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002948 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002949 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002950
Alexis Hunt1d792652011-01-08 20:30:50 +00002951 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002952 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002953 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002954 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002955 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002956}
2957
Sebastian Redl22653ba2011-08-30 19:58:05 +00002958// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002959static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2960 if (T.isNull()) T = E->getType();
2961 QualType TargetType = SemaRef.BuildReferenceType(
2962 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002963 SourceLocation ExprLoc = E->getLocStart();
2964 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2965 TargetType, ExprLoc);
2966
2967 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2968 SourceRange(ExprLoc, ExprLoc),
2969 E->getSourceRange()).take();
2970}
2971
Anders Carlsson1b00e242010-04-23 03:10:23 +00002972/// ImplicitInitializerKind - How an implicit base or member initializer should
2973/// initialize its base or member.
2974enum ImplicitInitializerKind {
2975 IIK_Default,
2976 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002977 IIK_Move,
2978 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002979};
2980
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002981static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002982BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002983 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002984 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002985 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002986 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002987 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002988 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2989 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002990
John McCalldadc5752010-08-24 06:29:42 +00002991 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002992
2993 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002994 case IIK_Inherit: {
2995 const CXXRecordDecl *Inherited =
2996 Constructor->getInheritedConstructor()->getParent();
2997 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2998 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2999 // C++11 [class.inhctor]p8:
3000 // Each expression in the expression-list is of the form
3001 // static_cast<T&&>(p), where p is the name of the corresponding
3002 // constructor parameter and T is the declared type of p.
3003 SmallVector<Expr*, 16> Args;
3004 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3005 ParmVarDecl *PD = Constructor->getParamDecl(I);
3006 ExprResult ArgExpr =
3007 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3008 VK_LValue, SourceLocation());
3009 if (ArgExpr.isInvalid())
3010 return true;
3011 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3012 }
3013
3014 InitializationKind InitKind = InitializationKind::CreateDirect(
3015 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003017 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3018 break;
3019 }
3020 }
3021 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003022 case IIK_Default: {
3023 InitializationKind InitKind
3024 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003025 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3026 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003027 break;
3028 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003029
Sebastian Redl22653ba2011-08-30 19:58:05 +00003030 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003031 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003032 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003033 ParmVarDecl *Param = Constructor->getParamDecl(0);
3034 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003035
Anders Carlsson1b00e242010-04-23 03:10:23 +00003036 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003037 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003038 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003039 Constructor->getLocation(), ParamType,
3040 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003041
Eli Friedmanfa0df832012-02-02 03:46:19 +00003042 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3043
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003044 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003045 QualType ArgTy =
3046 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3047 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003048
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049 if (Moving) {
3050 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3051 }
3052
John McCallcf142162010-08-07 06:22:56 +00003053 CXXCastPath BasePath;
3054 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003055 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3056 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003057 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003058 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003059
Anders Carlsson1b00e242010-04-23 03:10:23 +00003060 InitializationKind InitKind
3061 = InitializationKind::CreateDirect(Constructor->getLocation(),
3062 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003063 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3064 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003065 break;
3066 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003067 }
John McCallb268a282010-08-23 23:25:46 +00003068
Douglas Gregora40433a2010-12-07 00:41:46 +00003069 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003070 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003071 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003072
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003073 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003074 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003075 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3076 SourceLocation()),
3077 BaseSpec->isVirtual(),
3078 SourceLocation(),
3079 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003080 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003081 SourceLocation());
3082
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003083 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003084}
3085
Sebastian Redl22653ba2011-08-30 19:58:05 +00003086static bool RefersToRValueRef(Expr *MemRef) {
3087 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3088 return Referenced->getType()->isRValueReferenceType();
3089}
3090
Anders Carlsson3c1db572010-04-23 02:15:47 +00003091static bool
3092BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003093 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003094 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003095 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003096 if (Field->isInvalidDecl())
3097 return true;
3098
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003099 SourceLocation Loc = Constructor->getLocation();
3100
Sebastian Redl22653ba2011-08-30 19:58:05 +00003101 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3102 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003103 ParmVarDecl *Param = Constructor->getParamDecl(0);
3104 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003105
3106 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003107 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3108 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003109
Anders Carlsson423f5d82010-04-23 16:04:08 +00003110 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003111 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003112 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003113 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003114
Eli Friedmanfa0df832012-02-02 03:46:19 +00003115 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 if (Moving) {
3118 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3119 }
3120
Douglas Gregor94f9a482010-05-05 05:51:00 +00003121 // Build a reference to this field within the parameter.
3122 CXXScopeSpec SS;
3123 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3124 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003125 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3126 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003127 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003128 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003129 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003130 ParamType, Loc,
3131 /*IsArrow=*/false,
3132 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003133 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003134 /*FirstQualifierInScope=*/0,
3135 MemberLookup,
3136 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003137 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003138 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003139
3140 // C++11 [class.copy]p15:
3141 // - if a member m has rvalue reference type T&&, it is direct-initialized
3142 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 if (RefersToRValueRef(CtorArg.get())) {
3144 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003145 }
3146
Douglas Gregor94f9a482010-05-05 05:51:00 +00003147 // When the field we are copying is an array, create index variables for
3148 // each dimension of the array. We use these index variables to subscript
3149 // the source array, and other clients (e.g., CodeGen) will perform the
3150 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003151 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003152 QualType BaseType = Field->getType();
3153 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003154 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003155 while (const ConstantArrayType *Array
3156 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003157 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003158 // Create the iteration variable for this array index.
3159 IdentifierInfo *IterationVarName = 0;
3160 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003161 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003162 llvm::raw_svector_ostream OS(Str);
3163 OS << "__i" << IndexVariables.size();
3164 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3165 }
3166 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003167 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003168 IterationVarName, SizeType,
3169 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003170 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 IndexVariables.push_back(IterationVar);
3172
3173 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003174 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003175 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 assert(!IterationVarRef.isInvalid() &&
3177 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003178 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3179 assert(!IterationVarRef.isInvalid() &&
3180 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003181
Douglas Gregor94f9a482010-05-05 05:51:00 +00003182 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003183 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003184 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003185 Loc);
3186 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003188
Douglas Gregor94f9a482010-05-05 05:51:00 +00003189 BaseType = Array->getElementType();
3190 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003191
3192 // The array subscript expression is an lvalue, which is wrong for moving.
3193 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003194 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003195
Douglas Gregor94f9a482010-05-05 05:51:00 +00003196 // Construct the entity that we will be initializing. For an array, this
3197 // will be first element in the array, which may require several levels
3198 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003199 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003200 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003201 if (Indirect)
3202 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3203 else
3204 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3206 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3207 0,
3208 Entities.back()));
3209
3210 // Direct-initialize to use the copy constructor.
3211 InitializationKind InitKind =
3212 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3213
Sebastian Redle9c4e842011-09-04 18:14:28 +00003214 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003215 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003216
John McCalldadc5752010-08-24 06:29:42 +00003217 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003218 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003219 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003220 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003221 if (MemberInit.isInvalid())
3222 return true;
3223
Douglas Gregor493627b2011-08-10 15:22:55 +00003224 if (Indirect) {
3225 assert(IndexVariables.size() == 0 &&
3226 "Indirect field improperly initialized");
3227 CXXMemberInit
3228 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3229 Loc, Loc,
3230 MemberInit.takeAs<Expr>(),
3231 Loc);
3232 } else
3233 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3234 Loc, MemberInit.takeAs<Expr>(),
3235 Loc,
3236 IndexVariables.data(),
3237 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003238 return false;
3239 }
3240
Richard Smithc2bc61b2013-03-18 21:12:30 +00003241 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3242 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003243
Anders Carlsson3c1db572010-04-23 02:15:47 +00003244 QualType FieldBaseElementType =
3245 SemaRef.Context.getBaseElementType(Field->getType());
3246
Anders Carlsson3c1db572010-04-23 02:15:47 +00003247 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003248 InitializedEntity InitEntity
3249 = Indirect? InitializedEntity::InitializeMember(Indirect)
3250 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003251 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003252 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003253
3254 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3255 ExprResult MemberInit =
3256 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003257
Douglas Gregora40433a2010-12-07 00:41:46 +00003258 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003259 if (MemberInit.isInvalid())
3260 return true;
3261
Douglas Gregor493627b2011-08-10 15:22:55 +00003262 if (Indirect)
3263 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3264 Indirect, Loc,
3265 Loc,
3266 MemberInit.get(),
3267 Loc);
3268 else
3269 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3270 Field, Loc, Loc,
3271 MemberInit.get(),
3272 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003273 return false;
3274 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003275
Alexis Hunt8b455182011-05-17 00:19:05 +00003276 if (!Field->getParent()->isUnion()) {
3277 if (FieldBaseElementType->isReferenceType()) {
3278 SemaRef.Diag(Constructor->getLocation(),
3279 diag::err_uninitialized_member_in_ctor)
3280 << (int)Constructor->isImplicit()
3281 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3282 << 0 << Field->getDeclName();
3283 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3284 return true;
3285 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003286
Alexis Hunt8b455182011-05-17 00:19:05 +00003287 if (FieldBaseElementType.isConstQualified()) {
3288 SemaRef.Diag(Constructor->getLocation(),
3289 diag::err_uninitialized_member_in_ctor)
3290 << (int)Constructor->isImplicit()
3291 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3292 << 1 << Field->getDeclName();
3293 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3294 return true;
3295 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003296 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003297
David Blaikiebbafb8a2012-03-11 07:00:24 +00003298 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003299 FieldBaseElementType->isObjCRetainableType() &&
3300 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3301 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003302 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003303 // Default-initialize Objective-C pointers to NULL.
3304 CXXMemberInit
3305 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3306 Loc, Loc,
3307 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3308 Loc);
3309 return false;
3310 }
3311
Anders Carlsson3c1db572010-04-23 02:15:47 +00003312 // Nothing to initialize.
3313 CXXMemberInit = 0;
3314 return false;
3315}
John McCallbc83b3f2010-05-20 23:23:51 +00003316
3317namespace {
3318struct BaseAndFieldInfo {
3319 Sema &S;
3320 CXXConstructorDecl *Ctor;
3321 bool AnyErrorsInInits;
3322 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003323 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003324 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003325 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003326
3327 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3328 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003329 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3330 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003331 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003332 else if (Generated && Ctor->isMoveConstructor())
3333 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003334 else if (Ctor->getInheritedConstructor())
3335 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003336 else
3337 IIK = IIK_Default;
3338 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003339
3340 bool isImplicitCopyOrMove() const {
3341 switch (IIK) {
3342 case IIK_Copy:
3343 case IIK_Move:
3344 return true;
3345
3346 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003347 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003348 return false;
3349 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003350
3351 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003352 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003353
3354 bool addFieldInitializer(CXXCtorInitializer *Init) {
3355 AllToInit.push_back(Init);
3356
3357 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003358 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003359 S.UnusedPrivateFields.remove(Init->getAnyMember());
3360
3361 return false;
3362 }
John McCallbc83b3f2010-05-20 23:23:51 +00003363
Richard Smithab44d5b2013-12-10 08:25:00 +00003364 bool isInactiveUnionMember(FieldDecl *Field) {
3365 RecordDecl *Record = Field->getParent();
3366 if (!Record->isUnion())
3367 return false;
3368
Richard Smith8d183852013-12-10 20:56:03 +00003369 if (FieldDecl *Active =
3370 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003371 return Active != Field->getCanonicalDecl();
3372
3373 // In an implicit copy or move constructor, ignore any in-class initializer.
3374 if (isImplicitCopyOrMove())
3375 return true;
3376
3377 // If there's no explicit initialization, the field is active only if it
3378 // has an in-class initializer...
3379 if (Field->hasInClassInitializer())
3380 return false;
3381 // ... or it's an anonymous struct or union whose class has an in-class
3382 // initializer.
3383 if (!Field->isAnonymousStructOrUnion())
3384 return true;
3385 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3386 return !FieldRD->hasInClassInitializer();
3387 }
3388
3389 /// \brief Determine whether the given field is, or is within, a union member
3390 /// that is inactive (because there was an initializer given for a different
3391 /// member of the union, or because the union was not initialized at all).
3392 bool isWithinInactiveUnionMember(FieldDecl *Field,
3393 IndirectFieldDecl *Indirect) {
3394 if (!Indirect)
3395 return isInactiveUnionMember(Field);
3396
Aaron Ballman29c94602014-03-07 18:36:15 +00003397 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003398 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003399 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003400 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003401 }
3402 return false;
3403 }
3404};
Richard Smithc94ec842011-09-19 13:34:43 +00003405}
3406
Douglas Gregor10f939c2011-11-02 23:04:16 +00003407/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3408/// array type.
3409static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3410 if (T->isIncompleteArrayType())
3411 return true;
3412
3413 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3414 if (!ArrayT->getSize())
3415 return true;
3416
3417 T = ArrayT->getElementType();
3418 }
3419
3420 return false;
3421}
3422
Richard Smith938f40b2011-06-11 17:19:42 +00003423static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003424 FieldDecl *Field,
3425 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003426 if (Field->isInvalidDecl())
3427 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003428
Chandler Carruth139e9622010-06-30 02:59:29 +00003429 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003430 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3431 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003432
Richard Smithab44d5b2013-12-10 08:25:00 +00003433 // C++11 [class.base.init]p8:
3434 // if the entity is a non-static data member that has a
3435 // brace-or-equal-initializer and either
3436 // -- the constructor's class is a union and no other variant member of that
3437 // union is designated by a mem-initializer-id or
3438 // -- the constructor's class is not a union, and, if the entity is a member
3439 // of an anonymous union, no other member of that union is designated by
3440 // a mem-initializer-id,
3441 // the entity is initialized as specified in [dcl.init].
3442 //
3443 // We also apply the same rules to handle anonymous structs within anonymous
3444 // unions.
3445 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3446 return false;
3447
Douglas Gregor7db3e952011-11-28 20:03:15 +00003448 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003449 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3450 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003451 CXXCtorInitializer *Init;
3452 if (Indirect)
3453 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3454 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003455 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003456 SourceLocation());
3457 else
3458 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3459 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003460 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003461 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003462 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003463 }
3464
Douglas Gregor10f939c2011-11-02 23:04:16 +00003465 // Don't initialize incomplete or zero-length arrays.
3466 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3467 return false;
3468
John McCallbc83b3f2010-05-20 23:23:51 +00003469 // Don't try to build an implicit initializer if there were semantic
3470 // errors in any of the initializers (and therefore we might be
3471 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003472 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003473 return false;
3474
Alexis Hunt1d792652011-01-08 20:30:50 +00003475 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003476 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3477 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003478 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003479
Richard Smith0a8cfc72012-08-07 21:30:42 +00003480 if (!Init)
3481 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003482
Richard Smith0a8cfc72012-08-07 21:30:42 +00003483 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003484}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003485
3486bool
3487Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3488 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003489 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003490 Constructor->setNumCtorInitializers(1);
3491 CXXCtorInitializer **initializer =
3492 new (Context) CXXCtorInitializer*[1];
3493 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3494 Constructor->setCtorInitializers(initializer);
3495
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003496 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003497 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003498 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3499 }
3500
Alexis Hunte2622992011-05-05 00:05:47 +00003501 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003502
Alexis Hunt61bc1732011-05-01 07:04:31 +00003503 return false;
3504}
Douglas Gregor493627b2011-08-10 15:22:55 +00003505
David Blaikie3fc2f912013-01-17 05:26:25 +00003506bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3507 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003508 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003509 // Just store the initializers as written, they will be checked during
3510 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003511 if (!Initializers.empty()) {
3512 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003513 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003514 new (Context) CXXCtorInitializer*[Initializers.size()];
3515 memcpy(baseOrMemberInitializers, Initializers.data(),
3516 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003517 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003518 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003519
3520 // Let template instantiation know whether we had errors.
3521 if (AnyErrors)
3522 Constructor->setInvalidDecl();
3523
Anders Carlssondb0a9652010-04-02 06:26:44 +00003524 return false;
3525 }
3526
John McCallbc83b3f2010-05-20 23:23:51 +00003527 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003528
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003529 // We need to build the initializer AST according to order of construction
3530 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003531 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003532 if (!ClassDecl)
3533 return true;
3534
Eli Friedman9cf6b592009-11-09 19:20:36 +00003535 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003536
David Blaikie3fc2f912013-01-17 05:26:25 +00003537 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003538 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003539
Anders Carlssondb0a9652010-04-02 06:26:44 +00003540 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003541 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003542 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003543 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003544
3545 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003546 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003547 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003548 if (FD && FD->getParent()->isUnion())
3549 Info.ActiveUnionMember.insert(std::make_pair(
3550 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3551 }
3552 } else if (FieldDecl *FD = Member->getMember()) {
3553 if (FD->getParent()->isUnion())
3554 Info.ActiveUnionMember.insert(std::make_pair(
3555 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3556 }
3557 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003558 }
3559
Anders Carlsson43c64af2010-04-21 19:52:01 +00003560 // Keep track of the direct virtual bases.
3561 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003562 for (auto &I : ClassDecl->bases()) {
3563 if (I.isVirtual())
3564 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003565 }
3566
Anders Carlssondb0a9652010-04-02 06:26:44 +00003567 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003568 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003569 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003570 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003571 // [class.base.init]p7, per DR257:
3572 // A mem-initializer where the mem-initializer-id names a virtual base
3573 // class is ignored during execution of a constructor of any class that
3574 // is not the most derived class.
3575 if (ClassDecl->isAbstract()) {
3576 // FIXME: Provide a fixit to remove the base specifier. This requires
3577 // tracking the location of the associated comma for a base specifier.
3578 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003579 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003580 DiagnoseAbstractType(ClassDecl);
3581 }
3582
John McCallbc83b3f2010-05-20 23:23:51 +00003583 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003584 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3585 // [class.base.init]p8, per DR257:
3586 // If a given [...] base class is not named by a mem-initializer-id
3587 // [...] and the entity is not a virtual base class of an abstract
3588 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003589 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003590 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003591 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003592 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003593 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003594 HadError = true;
3595 continue;
3596 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003597
John McCallbc83b3f2010-05-20 23:23:51 +00003598 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003599 }
3600 }
Mike Stump11289f42009-09-09 15:08:12 +00003601
John McCallbc83b3f2010-05-20 23:23:51 +00003602 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003603 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003604 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003605 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003606 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003607
Alexis Hunt1d792652011-01-08 20:30:50 +00003608 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003609 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003610 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003611 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003612 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003613 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003614 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003615 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003616 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003617 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003618 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003619
John McCallbc83b3f2010-05-20 23:23:51 +00003620 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003621 }
3622 }
Mike Stump11289f42009-09-09 15:08:12 +00003623
John McCallbc83b3f2010-05-20 23:23:51 +00003624 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003625 for (auto *Mem : ClassDecl->decls()) {
3626 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003627 // C++ [class.bit]p2:
3628 // A declaration for a bit-field that omits the identifier declares an
3629 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3630 // initialized.
3631 if (F->isUnnamedBitfield())
3632 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003633
Sebastian Redl22653ba2011-08-30 19:58:05 +00003634 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003635 // handle anonymous struct/union fields based on their individual
3636 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003637 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003638 continue;
3639
3640 if (CollectFieldInitializer(*this, Info, F))
3641 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003642 continue;
3643 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003644
3645 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003646 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003647 continue;
3648
Aaron Ballman629afae2014-03-07 19:56:05 +00003649 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003650 if (F->getType()->isIncompleteArrayType()) {
3651 assert(ClassDecl->hasFlexibleArrayMember() &&
3652 "Incomplete array type is not valid");
3653 continue;
3654 }
3655
Douglas Gregor493627b2011-08-10 15:22:55 +00003656 // Initialize each field of an anonymous struct individually.
3657 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3658 HadError = true;
3659
3660 continue;
3661 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
David Blaikie3fc2f912013-01-17 05:26:25 +00003664 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003665 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003666 Constructor->setNumCtorInitializers(NumInitializers);
3667 CXXCtorInitializer **baseOrMemberInitializers =
3668 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003669 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003670 NumInitializers * sizeof(CXXCtorInitializer*));
3671 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003672
John McCalla6309952010-03-16 21:39:52 +00003673 // Constructors implicitly reference the base and member
3674 // destructors.
3675 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3676 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003677 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003678
3679 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003680}
3681
David Blaikieb61b8152013-01-17 08:49:22 +00003682static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003683 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003684 const RecordDecl *RD = RT->getDecl();
3685 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003686 for (auto *Field : RD->fields())
3687 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003688 return;
3689 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003690 }
David Blaikieb61b8152013-01-17 08:49:22 +00003691 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003692}
3693
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003694static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3695 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003696}
3697
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003698static const void *GetKeyForMember(ASTContext &Context,
3699 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003700 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003701 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003702
David Blaikieb61b8152013-01-17 08:49:22 +00003703 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003704}
3705
David Blaikie3fc2f912013-01-17 05:26:25 +00003706static void DiagnoseBaseOrMemInitializerOrder(
3707 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3708 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003709 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003710 return;
Mike Stump11289f42009-09-09 15:08:12 +00003711
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003712 // Don't check initializers order unless the warning is enabled at the
3713 // location of at least one initializer.
3714 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003715 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003716 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003717 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3718 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003719 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003720 ShouldCheckOrder = true;
3721 break;
3722 }
3723 }
3724 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003725 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003726
John McCallbb7b6582010-04-10 07:37:23 +00003727 // Build the list of bases and members in the order that they'll
3728 // actually be initialized. The explicit initializers should be in
3729 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003730 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003731
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003732 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3733
John McCallbb7b6582010-04-10 07:37:23 +00003734 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003735 for (const auto &VBase : ClassDecl->vbases())
3736 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003737
John McCallbb7b6582010-04-10 07:37:23 +00003738 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003739 for (const auto &Base : ClassDecl->bases()) {
3740 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003741 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003742 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
John McCallbb7b6582010-04-10 07:37:23 +00003745 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003746 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003747 if (Field->isUnnamedBitfield())
3748 continue;
3749
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003750 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003751 }
3752
John McCallbb7b6582010-04-10 07:37:23 +00003753 unsigned NumIdealInits = IdealInitKeys.size();
3754 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003755
Alexis Hunt1d792652011-01-08 20:30:50 +00003756 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003757 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003758 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003759 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003760
3761 // Scan forward to try to find this initializer in the idealized
3762 // initializers list.
3763 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3764 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003765 break;
John McCallbb7b6582010-04-10 07:37:23 +00003766
3767 // If we didn't find this initializer, it must be because we
3768 // scanned past it on a previous iteration. That can only
3769 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003770 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003771 Sema::SemaDiagnosticBuilder D =
3772 SemaRef.Diag(PrevInit->getSourceLocation(),
3773 diag::warn_initializer_out_of_order);
3774
Francois Pichetd583da02010-12-04 09:14:42 +00003775 if (PrevInit->isAnyMemberInitializer())
3776 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003777 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003778 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003779
Francois Pichetd583da02010-12-04 09:14:42 +00003780 if (Init->isAnyMemberInitializer())
3781 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003782 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003783 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003784
3785 // Move back to the initializer's location in the ideal list.
3786 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3787 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003788 break;
John McCallbb7b6582010-04-10 07:37:23 +00003789
3790 assert(IdealIndex != NumIdealInits &&
3791 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003792 }
John McCallbb7b6582010-04-10 07:37:23 +00003793
3794 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003795 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003796}
3797
John McCall23eebd92010-04-10 09:28:51 +00003798namespace {
3799bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003800 CXXCtorInitializer *Init,
3801 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003802 if (!PrevInit) {
3803 PrevInit = Init;
3804 return false;
3805 }
3806
Douglas Gregorea306a12013-03-25 23:28:23 +00003807 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003808 S.Diag(Init->getSourceLocation(),
3809 diag::err_multiple_mem_initialization)
3810 << Field->getDeclName()
3811 << Init->getSourceRange();
3812 else {
John McCall424cec92011-01-19 06:33:43 +00003813 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003814 assert(BaseClass && "neither field nor base");
3815 S.Diag(Init->getSourceLocation(),
3816 diag::err_multiple_base_initialization)
3817 << QualType(BaseClass, 0)
3818 << Init->getSourceRange();
3819 }
3820 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3821 << 0 << PrevInit->getSourceRange();
3822
3823 return true;
3824}
3825
Alexis Hunt1d792652011-01-08 20:30:50 +00003826typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003827typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3828
3829bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003830 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003831 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003832 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003833 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003834 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003835
3836 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003837 if (Parent->isUnion()) {
3838 UnionEntry &En = Unions[Parent];
3839 if (En.first && En.first != Child) {
3840 S.Diag(Init->getSourceLocation(),
3841 diag::err_multiple_mem_union_initialization)
3842 << Field->getDeclName()
3843 << Init->getSourceRange();
3844 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3845 << 0 << En.second->getSourceRange();
3846 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003847 }
3848 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003849 En.first = Child;
3850 En.second = Init;
3851 }
David Blaikie0f65d592011-11-17 06:01:57 +00003852 if (!Parent->isAnonymousStructOrUnion())
3853 return false;
John McCall23eebd92010-04-10 09:28:51 +00003854 }
3855
3856 Child = Parent;
3857 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003858 }
John McCall23eebd92010-04-10 09:28:51 +00003859
3860 return false;
3861}
3862}
3863
Anders Carlssone857b292010-04-02 03:37:03 +00003864/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003865void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003866 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003867 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003868 bool AnyErrors) {
3869 if (!ConstructorDecl)
3870 return;
3871
3872 AdjustDeclIfTemplate(ConstructorDecl);
3873
3874 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003875 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003876
3877 if (!Constructor) {
3878 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3879 return;
3880 }
3881
John McCall23eebd92010-04-10 09:28:51 +00003882 // Mapping for the duplicate initializers check.
3883 // For member initializers, this is keyed with a FieldDecl*.
3884 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003885 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003886
3887 // Mapping for the inconsistent anonymous-union initializers check.
3888 RedundantUnionMap MemberUnions;
3889
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003890 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003891 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003892 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003893
Abramo Bagnara341d7832010-05-26 18:09:23 +00003894 // Set the source order index.
3895 Init->setSourceOrder(i);
3896
Francois Pichetd583da02010-12-04 09:14:42 +00003897 if (Init->isAnyMemberInitializer()) {
3898 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003899 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3900 CheckRedundantUnionInit(*this, Init, MemberUnions))
3901 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003902 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003903 const void *Key =
3904 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003905 if (CheckRedundantInit(*this, Init, Members[Key]))
3906 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003907 } else {
3908 assert(Init->isDelegatingInitializer());
3909 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003910 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003911 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003912 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003913 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003914 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003915 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003916 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003917 // Return immediately as the initializer is set.
3918 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003919 }
Anders Carlssone857b292010-04-02 03:37:03 +00003920 }
3921
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003922 if (HadError)
3923 return;
3924
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003926
David Blaikie3fc2f912013-01-17 05:26:25 +00003927 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003928
Richard Trieuef64e942013-10-25 00:56:00 +00003929 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003930}
3931
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003932void
John McCalla6309952010-03-16 21:39:52 +00003933Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3934 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003935 // Ignore dependent contexts. Also ignore unions, since their members never
3936 // have destructors implicitly called.
3937 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003938 return;
John McCall1064d7e2010-03-16 05:22:47 +00003939
3940 // FIXME: all the access-control diagnostics are positioned on the
3941 // field/base declaration. That's probably good; that said, the
3942 // user might reasonably want to know why the destructor is being
3943 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003944
Anders Carlssondee9a302009-11-17 04:44:12 +00003945 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003946 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003947 if (Field->isInvalidDecl())
3948 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003949
3950 // Don't destroy incomplete or zero-length arrays.
3951 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3952 continue;
3953
Anders Carlssondee9a302009-11-17 04:44:12 +00003954 QualType FieldType = Context.getBaseElementType(Field->getType());
3955
3956 const RecordType* RT = FieldType->getAs<RecordType>();
3957 if (!RT)
3958 continue;
3959
3960 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003961 if (FieldClassDecl->isInvalidDecl())
3962 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003963 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003964 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003965 // The destructor for an implicit anonymous union member is never invoked.
3966 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3967 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003968
Douglas Gregore71edda2010-07-01 22:47:18 +00003969 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003970 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003971 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003972 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003973 << Field->getDeclName()
3974 << FieldType);
3975
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003976 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003977 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003978 }
3979
John McCall1064d7e2010-03-16 05:22:47 +00003980 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3981
Anders Carlssondee9a302009-11-17 04:44:12 +00003982 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003983 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003984 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00003985 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003986
3987 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003988 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003989 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003990
John McCall1064d7e2010-03-16 05:22:47 +00003991 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003992 // If our base class is invalid, we probably can't get its dtor anyway.
3993 if (BaseClassDecl->isInvalidDecl())
3994 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003995 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003996 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003997
Douglas Gregore71edda2010-07-01 22:47:18 +00003998 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003999 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004000
4001 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004002 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004003 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004004 << Base.getType()
4005 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004006 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004007
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004008 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004009 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004010 }
4011
4012 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004013 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004014 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004015 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004016
4017 // Ignore direct virtual bases.
4018 if (DirectVirtualBases.count(RT))
4019 continue;
4020
John McCall1064d7e2010-03-16 05:22:47 +00004021 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004022 // If our base class is invalid, we probably can't get its dtor anyway.
4023 if (BaseClassDecl->isInvalidDecl())
4024 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004025 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004026 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004027
Douglas Gregore71edda2010-07-01 22:47:18 +00004028 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004029 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004030 if (CheckDestructorAccess(
4031 ClassDecl->getLocation(), Dtor,
4032 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004033 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004034 Context.getTypeDeclType(ClassDecl)) ==
4035 AR_accessible) {
4036 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004037 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004038 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4039 SourceRange(), DeclarationName(), 0);
4040 }
John McCall1064d7e2010-03-16 05:22:47 +00004041
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004042 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004043 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004044 }
4045}
4046
John McCall48871652010-08-21 09:40:31 +00004047void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004048 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004049 return;
Mike Stump11289f42009-09-09 15:08:12 +00004050
Mike Stump11289f42009-09-09 15:08:12 +00004051 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004052 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004053 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004054 DiagnoseUninitializedFields(*this, Constructor);
4055 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004056}
4057
Mike Stump11289f42009-09-09 15:08:12 +00004058bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004059 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004060 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4061 unsigned DiagID;
4062 AbstractDiagSelID SelID;
4063
4064 public:
4065 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4066 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004067
Craig Toppera798a9d2014-03-02 09:32:10 +00004068 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004069 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004070 if (SelID == -1)
4071 S.Diag(Loc, DiagID) << T;
4072 else
4073 S.Diag(Loc, DiagID) << SelID << T;
4074 }
4075 } Diagnoser(DiagID, SelID);
4076
4077 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004078}
4079
Anders Carlssoneabf7702009-08-27 00:13:57 +00004080bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004081 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004082 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004084
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004085 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004086 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004087
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004088 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004089 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004090 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004091 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004092
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004093 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004094 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004097 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004098 if (!RT)
4099 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004100
John McCall67da35c2010-02-04 22:26:26 +00004101 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004102
John McCall02db245d2010-08-18 09:41:07 +00004103 // We can't answer whether something is abstract until it has a
4104 // definition. If it's currently being defined, we'll walk back
4105 // over all the declarations when we have a full definition.
4106 const CXXRecordDecl *Def = RD->getDefinition();
4107 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004108 return false;
4109
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004110 if (!RD->isAbstract())
4111 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004112
Douglas Gregorae298422012-05-04 17:09:59 +00004113 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004114 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall02db245d2010-08-18 09:41:07 +00004116 return true;
4117}
4118
4119void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4120 // Check if we've already emitted the list of pure virtual functions
4121 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004122 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004123 return;
Mike Stump11289f42009-09-09 15:08:12 +00004124
Richard Smithbc46e432013-07-22 02:56:56 +00004125 // If the diagnostic is suppressed, don't emit the notes. We're only
4126 // going to emit them once, so try to attach them to a diagnostic we're
4127 // actually going to show.
4128 if (Diags.isLastDiagnosticIgnored())
4129 return;
4130
Douglas Gregor4165bd62010-03-23 23:47:56 +00004131 CXXFinalOverriderMap FinalOverriders;
4132 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Anders Carlssona2f74f32010-06-03 01:00:02 +00004134 // Keep a set of seen pure methods so we won't diagnose the same method
4135 // more than once.
4136 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4137
Douglas Gregor4165bd62010-03-23 23:47:56 +00004138 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4139 MEnd = FinalOverriders.end();
4140 M != MEnd;
4141 ++M) {
4142 for (OverridingMethods::iterator SO = M->second.begin(),
4143 SOEnd = M->second.end();
4144 SO != SOEnd; ++SO) {
4145 // C++ [class.abstract]p4:
4146 // A class is abstract if it contains or inherits at least one
4147 // pure virtual function for which the final overrider is pure
4148 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004149
Douglas Gregor4165bd62010-03-23 23:47:56 +00004150 //
4151 if (SO->second.size() != 1)
4152 continue;
4153
4154 if (!SO->second.front().Method->isPure())
4155 continue;
4156
Anders Carlssona2f74f32010-06-03 01:00:02 +00004157 if (!SeenPureMethods.insert(SO->second.front().Method))
4158 continue;
4159
Douglas Gregor4165bd62010-03-23 23:47:56 +00004160 Diag(SO->second.front().Method->getLocation(),
4161 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004162 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004163 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004164 }
4165
4166 if (!PureVirtualClassDiagSet)
4167 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4168 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169}
4170
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004171namespace {
John McCall02db245d2010-08-18 09:41:07 +00004172struct AbstractUsageInfo {
4173 Sema &S;
4174 CXXRecordDecl *Record;
4175 CanQualType AbstractType;
4176 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004177
John McCall02db245d2010-08-18 09:41:07 +00004178 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4179 : S(S), Record(Record),
4180 AbstractType(S.Context.getCanonicalType(
4181 S.Context.getTypeDeclType(Record))),
4182 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004183
John McCall02db245d2010-08-18 09:41:07 +00004184 void DiagnoseAbstractType() {
4185 if (Invalid) return;
4186 S.DiagnoseAbstractType(Record);
4187 Invalid = true;
4188 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004189
John McCall02db245d2010-08-18 09:41:07 +00004190 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4191};
4192
4193struct CheckAbstractUsage {
4194 AbstractUsageInfo &Info;
4195 const NamedDecl *Ctx;
4196
4197 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4198 : Info(Info), Ctx(Ctx) {}
4199
4200 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4201 switch (TL.getTypeLocClass()) {
4202#define ABSTRACT_TYPELOC(CLASS, PARENT)
4203#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004204 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004205#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004206 }
John McCall02db245d2010-08-18 09:41:07 +00004207 }
Mike Stump11289f42009-09-09 15:08:12 +00004208
John McCall02db245d2010-08-18 09:41:07 +00004209 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004210 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004211 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4212 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004213 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004214
4215 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004216 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004217 }
John McCall02db245d2010-08-18 09:41:07 +00004218 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004219
John McCall02db245d2010-08-18 09:41:07 +00004220 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4221 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall02db245d2010-08-18 09:41:07 +00004224 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4225 // Visit the type parameters from a permissive context.
4226 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4227 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4228 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4229 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4230 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4231 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004232 }
John McCall02db245d2010-08-18 09:41:07 +00004233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234
John McCall02db245d2010-08-18 09:41:07 +00004235 // Visit pointee types from a permissive context.
4236#define CheckPolymorphic(Type) \
4237 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4238 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4239 }
4240 CheckPolymorphic(PointerTypeLoc)
4241 CheckPolymorphic(ReferenceTypeLoc)
4242 CheckPolymorphic(MemberPointerTypeLoc)
4243 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004244 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004245
John McCall02db245d2010-08-18 09:41:07 +00004246 /// Handle all the types we haven't given a more specific
4247 /// implementation for above.
4248 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4249 // Every other kind of type that we haven't called out already
4250 // that has an inner type is either (1) sugar or (2) contains that
4251 // inner type in some way as a subobject.
4252 if (TypeLoc Next = TL.getNextTypeLoc())
4253 return Visit(Next, Sel);
4254
4255 // If there's no inner type and we're in a permissive context,
4256 // don't diagnose.
4257 if (Sel == Sema::AbstractNone) return;
4258
4259 // Check whether the type matches the abstract type.
4260 QualType T = TL.getType();
4261 if (T->isArrayType()) {
4262 Sel = Sema::AbstractArrayType;
4263 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004264 }
John McCall02db245d2010-08-18 09:41:07 +00004265 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4266 if (CT != Info.AbstractType) return;
4267
4268 // It matched; do some magic.
4269 if (Sel == Sema::AbstractArrayType) {
4270 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4271 << T << TL.getSourceRange();
4272 } else {
4273 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4274 << Sel << T << TL.getSourceRange();
4275 }
4276 Info.DiagnoseAbstractType();
4277 }
4278};
4279
4280void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4281 Sema::AbstractDiagSelID Sel) {
4282 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4283}
4284
4285}
4286
4287/// Check for invalid uses of an abstract type in a method declaration.
4288static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4289 CXXMethodDecl *MD) {
4290 // No need to do the check on definitions, which require that
4291 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004292 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004293 return;
4294
4295 // For safety's sake, just ignore it if we don't have type source
4296 // information. This should never happen for non-implicit methods,
4297 // but...
4298 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4299 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4300}
4301
4302/// Check for invalid uses of an abstract type within a class definition.
4303static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004305 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004306 if (D->isImplicit()) continue;
4307
4308 // Methods and method templates.
4309 if (isa<CXXMethodDecl>(D)) {
4310 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4311 } else if (isa<FunctionTemplateDecl>(D)) {
4312 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4313 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4314
4315 // Fields and static variables.
4316 } else if (isa<FieldDecl>(D)) {
4317 FieldDecl *FD = cast<FieldDecl>(D);
4318 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4319 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4320 } else if (isa<VarDecl>(D)) {
4321 VarDecl *VD = cast<VarDecl>(D);
4322 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4323 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4324
4325 // Nested classes and class templates.
4326 } else if (isa<CXXRecordDecl>(D)) {
4327 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4328 } else if (isa<ClassTemplateDecl>(D)) {
4329 CheckAbstractClassUsage(Info,
4330 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4331 }
4332 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004333}
4334
Douglas Gregorc99f1552009-12-03 18:33:45 +00004335/// \brief Perform semantic checks on a class definition that has been
4336/// completing, introducing implicitly-declared members, checking for
4337/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004338void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004339 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004340 return;
4341
John McCall02db245d2010-08-18 09:41:07 +00004342 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4343 AbstractUsageInfo Info(*this, Record);
4344 CheckAbstractClassUsage(Info, Record);
4345 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004346
4347 // If this is not an aggregate type and has no user-declared constructor,
4348 // complain about any non-static data members of reference or const scalar
4349 // type, since they will never get initializers.
4350 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004351 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4352 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004353 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004354 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004355 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004356 continue;
4357
Douglas Gregor454a5b62010-04-15 00:00:53 +00004358 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004359 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004360 if (!Complained) {
4361 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4362 << Record->getTagKind() << Record;
4363 Complained = true;
4364 }
4365
4366 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4367 << F->getType()->isReferenceType()
4368 << F->getDeclName();
4369 }
4370 }
4371 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004372
Anders Carlssone771e762011-01-25 18:08:22 +00004373 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004374 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004375
4376 if (Record->getIdentifier()) {
4377 // C++ [class.mem]p13:
4378 // If T is the name of a class, then each of the following shall have a
4379 // name different from T:
4380 // - every member of every anonymous union that is a member of class T.
4381 //
4382 // C++ [class.mem]p14:
4383 // In addition, if class T has a user-declared constructor (12.1), every
4384 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004385 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4386 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4387 ++I) {
4388 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004389 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4390 isa<IndirectFieldDecl>(D)) {
4391 Diag(D->getLocation(), diag::err_member_name_of_class)
4392 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004393 break;
4394 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004395 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004396 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004397
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004398 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004399 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004400 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004401 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004402 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4403 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4404 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004405
David Majnemera5433082013-10-18 00:33:31 +00004406 if (Record->isAbstract()) {
4407 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4408 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4409 << FA->isSpelledAsSealed();
4410 DiagnoseAbstractType(Record);
4411 }
David Blaikie348df502012-09-21 03:21:07 +00004412 }
4413
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004414 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004415 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004416 // See if a method overloads virtual methods in a base
4417 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004418 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004419 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004420
4421 // Check whether the explicitly-defaulted special members are valid.
4422 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004423 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004424
4425 // For an explicitly defaulted or deleted special member, we defer
4426 // determining triviality until the class is complete. That time is now!
4427 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004428 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004429 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004430 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004431
4432 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004433 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004434 }
4435 }
4436 }
4437 }
4438
4439 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4440 // function that is not a constructor declares that member function to be
4441 // const. [...] The class of which that function is a member shall be
4442 // a literal type.
4443 //
4444 // If the class has virtual bases, any constexpr members will already have
4445 // been diagnosed by the checks performed on the member declaration, so
4446 // suppress this (less useful) diagnostic.
4447 //
4448 // We delay this until we know whether an explicitly-defaulted (or deleted)
4449 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004450 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004451 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004452 for (const auto *M : Record->methods()) {
4453 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004454 switch (Record->getTemplateSpecializationKind()) {
4455 case TSK_ImplicitInstantiation:
4456 case TSK_ExplicitInstantiationDeclaration:
4457 case TSK_ExplicitInstantiationDefinition:
4458 // If a template instantiates to a non-literal type, but its members
4459 // instantiate to constexpr functions, the template is technically
4460 // ill-formed, but we allow it for sanity.
4461 continue;
4462
4463 case TSK_Undeclared:
4464 case TSK_ExplicitSpecialization:
4465 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4466 diag::err_constexpr_method_non_literal);
4467 break;
4468 }
4469
4470 // Only produce one error per class.
4471 break;
4472 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004473 }
4474 }
Sebastian Redl08905022011-02-05 19:23:19 +00004475
John McCall95833f32014-02-27 20:30:49 +00004476 // ms_struct is a request to use the same ABI rules as MSVC. Check
4477 // whether this class uses any C++ features that are implemented
4478 // completely differently in MSVC, and if so, emit a diagnostic.
4479 // That diagnostic defaults to an error, but we allow projects to
4480 // map it down to a warning (or ignore it). It's a fairly common
4481 // practice among users of the ms_struct pragma to mass-annotate
4482 // headers, sweeping up a bunch of types that the project doesn't
4483 // really rely on MSVC-compatible layout for. We must therefore
4484 // support "ms_struct except for C++ stuff" as a secondary ABI.
4485 if (Record->isMsStruct(Context) &&
4486 (Record->isPolymorphic() || Record->getNumBases())) {
4487 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004488 }
4489
Richard Smithc2bc61b2013-03-18 21:12:30 +00004490 // Declare inheriting constructors. We do this eagerly here because:
4491 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004492 // constructors from different classes.
4493 // - The lazy declaration of the other implicit constructors is so as to not
4494 // waste space and performance on classes that are not meant to be
4495 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004496 // have inheriting constructors.
4497 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004498}
4499
Richard Smith41c35d62013-11-27 03:39:20 +00004500/// Look up the special member function that would be called by a special
4501/// member function for a subobject of class type.
4502///
4503/// \param Class The class type of the subobject.
4504/// \param CSM The kind of special member function.
4505/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4506/// \param ConstRHS True if this is a copy operation with a const object
4507/// on its RHS, that is, if the argument to the outer special member
4508/// function is 'const' and this is not a field marked 'mutable'.
4509static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4510 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4511 unsigned FieldQuals, bool ConstRHS) {
4512 unsigned LHSQuals = 0;
4513 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4514 LHSQuals = FieldQuals;
4515
4516 unsigned RHSQuals = FieldQuals;
4517 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4518 RHSQuals = 0;
4519 else if (ConstRHS)
4520 RHSQuals |= Qualifiers::Const;
4521
4522 return S.LookupSpecialMember(Class, CSM,
4523 RHSQuals & Qualifiers::Const,
4524 RHSQuals & Qualifiers::Volatile,
4525 false,
4526 LHSQuals & Qualifiers::Const,
4527 LHSQuals & Qualifiers::Volatile);
4528}
4529
Richard Smithb5800092012-06-10 05:43:50 +00004530/// Is the special member function which would be selected to perform the
4531/// specified operation on the specified class type a constexpr constructor?
4532static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4533 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004534 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004535 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004536 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004537 if (!SMOR || !SMOR->getMethod())
4538 // A constructor we wouldn't select can't be "involved in initializing"
4539 // anything.
4540 return true;
4541 return SMOR->getMethod()->isConstexpr();
4542}
4543
4544/// Determine whether the specified special member function would be constexpr
4545/// if it were implicitly defined.
4546static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4547 Sema::CXXSpecialMember CSM,
4548 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004549 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004550 return false;
4551
4552 // C++11 [dcl.constexpr]p4:
4553 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004554 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004555 switch (CSM) {
4556 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004557 // Since default constructor lookup is essentially trivial (and cannot
4558 // involve, for instance, template instantiation), we compute whether a
4559 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4560 //
4561 // This is important for performance; we need to know whether the default
4562 // constructor is constexpr to determine whether the type is a literal type.
4563 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4564
Richard Smithb5800092012-06-10 05:43:50 +00004565 case Sema::CXXCopyConstructor:
4566 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004567 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004568 break;
4569
4570 case Sema::CXXCopyAssignment:
4571 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004572 if (!S.getLangOpts().CPlusPlus1y)
4573 return false;
4574 // In C++1y, we need to perform overload resolution.
4575 Ctor = false;
4576 break;
4577
Richard Smithb5800092012-06-10 05:43:50 +00004578 case Sema::CXXDestructor:
4579 case Sema::CXXInvalid:
4580 return false;
4581 }
4582
4583 // -- if the class is a non-empty union, or for each non-empty anonymous
4584 // union member of a non-union class, exactly one non-static data member
4585 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004586 //
4587 // If we squint, this is guaranteed, since exactly one non-static data member
4588 // will be initialized (if the constructor isn't deleted), we just don't know
4589 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004590 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004591 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004592
4593 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004594 if (Ctor && ClassDecl->getNumVBases())
4595 return false;
4596
4597 // C++1y [class.copy]p26:
4598 // -- [the class] is a literal type, and
4599 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004600 return false;
4601
4602 // -- every constructor involved in initializing [...] base class
4603 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004604 // -- the assignment operator selected to copy/move each direct base
4605 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004606 for (const auto &B : ClassDecl->bases()) {
4607 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004608 if (!BaseType) continue;
4609
4610 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004611 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004612 return false;
4613 }
4614
4615 // -- every constructor involved in initializing non-static data members
4616 // [...] shall be a constexpr constructor;
4617 // -- every non-static data member and base class sub-object shall be
4618 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004619 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004620 // thereof), the assignment operator selected to copy/move that member is
4621 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004622 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004623 if (F->isInvalidDecl())
4624 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004625 QualType BaseType = S.Context.getBaseElementType(F->getType());
4626 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004627 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004628 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4629 BaseType.getCVRQualifiers(),
4630 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004631 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004632 }
4633 }
4634
4635 // All OK, it's constexpr!
4636 return true;
4637}
4638
Richard Smithd3b5c9082012-07-27 04:22:15 +00004639static Sema::ImplicitExceptionSpecification
4640computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4641 switch (S.getSpecialMember(MD)) {
4642 case Sema::CXXDefaultConstructor:
4643 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4644 case Sema::CXXCopyConstructor:
4645 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4646 case Sema::CXXCopyAssignment:
4647 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4648 case Sema::CXXMoveConstructor:
4649 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4650 case Sema::CXXMoveAssignment:
4651 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4652 case Sema::CXXDestructor:
4653 return S.ComputeDefaultedDtorExceptionSpec(MD);
4654 case Sema::CXXInvalid:
4655 break;
4656 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004657 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4658 "only special members have implicit exception specs");
4659 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004660}
4661
Richard Smith7f782272012-07-30 23:48:14 +00004662static void
4663updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4664 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4665 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4666 ExceptSpec.getEPI(EPI);
Alp Toker314cc812014-01-25 16:55:45 +00004667 FD->setType(S.Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004668 FPT->getParamTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004669}
4670
Reid Kleckner78af0702013-08-27 23:08:25 +00004671static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4672 CXXMethodDecl *MD) {
4673 FunctionProtoType::ExtProtoInfo EPI;
4674
4675 // Build an exception specification pointing back at this member.
4676 EPI.ExceptionSpecType = EST_Unevaluated;
4677 EPI.ExceptionSpecDecl = MD;
4678
4679 // Set the calling convention to the default for C++ instance methods.
4680 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4681 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4682 /*IsCXXMethod=*/true));
4683 return EPI;
4684}
4685
Richard Smithd3b5c9082012-07-27 04:22:15 +00004686void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4687 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4688 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4689 return;
4690
Richard Smith7f782272012-07-30 23:48:14 +00004691 // Evaluate the exception specification.
4692 ImplicitExceptionSpecification ExceptSpec =
4693 computeImplicitExceptionSpec(*this, Loc, MD);
4694
4695 // Update the type of the special member to use it.
4696 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4697
4698 // A user-provided destructor can be defined outside the class. When that
4699 // happens, be sure to update the exception specification on both
4700 // declarations.
4701 const FunctionProtoType *CanonicalFPT =
4702 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4703 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4704 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4705 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004706}
4707
Richard Smithb9e90b12012-05-15 04:39:51 +00004708void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4709 CXXRecordDecl *RD = MD->getParent();
4710 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004711
Richard Smithb9e90b12012-05-15 04:39:51 +00004712 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4713 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004714
4715 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004716 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004717 bool First = MD == MD->getCanonicalDecl();
4718
4719 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004720
4721 // C++11 [dcl.fct.def.default]p1:
4722 // A function that is explicitly defaulted shall
4723 // -- be a special member function (checked elsewhere),
4724 // -- have the same type (except for ref-qualifiers, and except that a
4725 // copy operation can take a non-const reference) as an implicit
4726 // declaration, and
4727 // -- not have default arguments.
4728 unsigned ExpectedParams = 1;
4729 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4730 ExpectedParams = 0;
4731 if (MD->getNumParams() != ExpectedParams) {
4732 // This also checks for default arguments: a copy or move constructor with a
4733 // default argument is classified as a default constructor, and assignment
4734 // operations and destructors can't have default arguments.
4735 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4736 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004737 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004738 } else if (MD->isVariadic()) {
4739 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4740 << CSM << MD->getSourceRange();
4741 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004742 }
4743
Richard Smithb9e90b12012-05-15 04:39:51 +00004744 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004745
Richard Smithb5800092012-06-10 05:43:50 +00004746 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004747 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004748 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004749 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004750 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004751
Richard Smithb9e90b12012-05-15 04:39:51 +00004752 QualType ReturnType = Context.VoidTy;
4753 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4754 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004755 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004756 QualType ExpectedReturnType =
4757 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4758 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4759 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4760 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4761 HadError = true;
4762 }
4763
4764 // A defaulted special member cannot have cv-qualifiers.
4765 if (Type->getTypeQuals()) {
4766 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004767 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004768 HadError = true;
4769 }
4770 }
4771
4772 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004773 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004774 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004775 if (ExpectedParams && ArgType->isReferenceType()) {
4776 // Argument must be reference to possibly-const T.
4777 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004778 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004779
4780 if (ReferentType.isVolatileQualified()) {
4781 Diag(MD->getLocation(),
4782 diag::err_defaulted_special_member_volatile_param) << CSM;
4783 HadError = true;
4784 }
4785
Richard Smithb5800092012-06-10 05:43:50 +00004786 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004787 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4788 Diag(MD->getLocation(),
4789 diag::err_defaulted_special_member_copy_const_param)
4790 << (CSM == CXXCopyAssignment);
4791 // FIXME: Explain why this special member can't be const.
4792 } else {
4793 Diag(MD->getLocation(),
4794 diag::err_defaulted_special_member_move_const_param)
4795 << (CSM == CXXMoveAssignment);
4796 }
4797 HadError = true;
4798 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004799 } else if (ExpectedParams) {
4800 // A copy assignment operator can take its argument by value, but a
4801 // defaulted one cannot.
4802 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004803 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004804 HadError = true;
4805 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004806
Richard Smithcc36f692011-12-22 02:22:31 +00004807 // C++11 [dcl.fct.def.default]p2:
4808 // An explicitly-defaulted function may be declared constexpr only if it
4809 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004810 // Do not apply this rule to members of class templates, since core issue 1358
4811 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004812 // functions which cannot be constexpr (for non-constructors in C++11 and for
4813 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004814 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4815 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004816 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4817 : isa<CXXConstructorDecl>(MD)) &&
4818 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004819 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4820 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004821 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004822 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004823 }
Richard Smithbd305122012-12-11 01:14:52 +00004824
Richard Smithcc36f692011-12-22 02:22:31 +00004825 // and may have an explicit exception-specification only if it is compatible
4826 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004827 if (Type->hasExceptionSpec()) {
4828 // Delay the check if this is the first declaration of the special member,
4829 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004830 if (First) {
4831 // If the exception specification needs to be instantiated, do so now,
4832 // before we clobber it with an EST_Unevaluated specification below.
4833 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4834 InstantiateExceptionSpec(MD->getLocStart(), MD);
4835 Type = MD->getType()->getAs<FunctionProtoType>();
4836 }
Richard Smithbd305122012-12-11 01:14:52 +00004837 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004838 } else
Richard Smithbd305122012-12-11 01:14:52 +00004839 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4840 }
Richard Smithcc36f692011-12-22 02:22:31 +00004841
4842 // If a function is explicitly defaulted on its first declaration,
4843 if (First) {
4844 // -- it is implicitly considered to be constexpr if the implicit
4845 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004846 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004847
Richard Smithb9e90b12012-05-15 04:39:51 +00004848 // -- it is implicitly considered to have the same exception-specification
4849 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004850 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4851 EPI.ExceptionSpecType = EST_Unevaluated;
4852 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004853 MD->setType(Context.getFunctionType(ReturnType,
4854 ArrayRef<QualType>(&ArgType,
4855 ExpectedParams),
4856 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004857 }
4858
Richard Smithb9e90b12012-05-15 04:39:51 +00004859 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004860 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004861 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004862 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004863 // C++11 [dcl.fct.def.default]p4:
4864 // [For a] user-provided explicitly-defaulted function [...] if such a
4865 // function is implicitly defined as deleted, the program is ill-formed.
4866 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004867 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004868 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004869 }
4870 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004871
Richard Smithb9e90b12012-05-15 04:39:51 +00004872 if (HadError)
4873 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004874}
4875
Richard Smithbd305122012-12-11 01:14:52 +00004876/// Check whether the exception specification provided for an
4877/// explicitly-defaulted special member matches the exception specification
4878/// that would have been generated for an implicit special member, per
4879/// C++11 [dcl.fct.def.default]p2.
4880void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4881 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4882 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004883 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4884 /*IsCXXMethod=*/true);
4885 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004886 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4887 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004888 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004889
4890 // Ensure that it matches.
4891 CheckEquivalentExceptionSpec(
4892 PDiag(diag::err_incorrect_defaulted_exception_spec)
4893 << getSpecialMember(MD), PDiag(),
4894 ImplicitType, SourceLocation(),
4895 SpecifiedType, MD->getLocation());
4896}
4897
Alp Tokerae3a9442013-10-18 05:54:19 +00004898void Sema::CheckDelayedMemberExceptionSpecs() {
4899 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4900 2> Checks;
4901 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004902
Alp Tokerae3a9442013-10-18 05:54:19 +00004903 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4904 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4905
4906 // Perform any deferred checking of exception specifications for virtual
4907 // destructors.
4908 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4909 const CXXDestructorDecl *Dtor = Checks[i].first;
4910 assert(!Dtor->getParent()->isDependentType() &&
4911 "Should not ever add destructors of templates into the list.");
4912 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4913 }
4914
4915 // Check that any explicitly-defaulted methods have exception specifications
4916 // compatible with their implicit exception specifications.
4917 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4918 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4919 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004920}
4921
Richard Smithd951a1d2012-02-18 02:02:13 +00004922namespace {
4923struct SpecialMemberDeletionInfo {
4924 Sema &S;
4925 CXXMethodDecl *MD;
4926 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004927 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004928
4929 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004930 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004931 SourceLocation Loc;
4932
4933 bool AllFieldsAreConst;
4934
4935 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004936 Sema::CXXSpecialMember CSM, bool Diagnose)
4937 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004938 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004939 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004940 AllFieldsAreConst(true) {
4941 switch (CSM) {
4942 case Sema::CXXDefaultConstructor:
4943 case Sema::CXXCopyConstructor:
4944 IsConstructor = true;
4945 break;
4946 case Sema::CXXMoveConstructor:
4947 IsConstructor = true;
4948 IsMove = true;
4949 break;
4950 case Sema::CXXCopyAssignment:
4951 IsAssignment = true;
4952 break;
4953 case Sema::CXXMoveAssignment:
4954 IsAssignment = true;
4955 IsMove = true;
4956 break;
4957 case Sema::CXXDestructor:
4958 break;
4959 case Sema::CXXInvalid:
4960 llvm_unreachable("invalid special member kind");
4961 }
4962
4963 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004964 if (const ReferenceType *RT =
4965 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4966 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004967 }
4968 }
4969
4970 bool inUnion() const { return MD->getParent()->isUnion(); }
4971
4972 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004973 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004974 unsigned Quals, bool IsMutable) {
4975 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4976 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004977 }
4978
Richard Smith852265f2012-03-30 20:53:28 +00004979 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004980
Richard Smith852265f2012-03-30 20:53:28 +00004981 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004982 bool shouldDeleteForField(FieldDecl *FD);
4983 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004984
Richard Smithaf136f82012-07-18 03:51:16 +00004985 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4986 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004987 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4988 Sema::SpecialMemberOverloadResult *SMOR,
4989 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004990
4991 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004992};
4993}
4994
John McCalld4274212012-04-09 20:53:23 +00004995/// Is the given special member inaccessible when used on the given
4996/// sub-object.
4997bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4998 CXXMethodDecl *target) {
4999 /// If we're operating on a base class, the object type is the
5000 /// type of this special member.
5001 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005002 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005003 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5004 objectTy = S.Context.getTypeDeclType(MD->getParent());
5005 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5006
5007 // If we're operating on a field, the object type is the type of the field.
5008 } else {
5009 objectTy = S.Context.getTypeDeclType(target->getParent());
5010 }
5011
5012 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5013}
5014
Richard Smith852265f2012-03-30 20:53:28 +00005015/// Check whether we should delete a special member due to the implicit
5016/// definition containing a call to a special member of a subobject.
5017bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5018 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5019 bool IsDtorCallInCtor) {
5020 CXXMethodDecl *Decl = SMOR->getMethod();
5021 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5022
5023 int DiagKind = -1;
5024
5025 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5026 DiagKind = !Decl ? 0 : 1;
5027 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5028 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005029 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005030 DiagKind = 3;
5031 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5032 !Decl->isTrivial()) {
5033 // A member of a union must have a trivial corresponding special member.
5034 // As a weird special case, a destructor call from a union's constructor
5035 // must be accessible and non-deleted, but need not be trivial. Such a
5036 // destructor is never actually called, but is semantically checked as
5037 // if it were.
5038 DiagKind = 4;
5039 }
5040
5041 if (DiagKind == -1)
5042 return false;
5043
5044 if (Diagnose) {
5045 if (Field) {
5046 S.Diag(Field->getLocation(),
5047 diag::note_deleted_special_member_class_subobject)
5048 << CSM << MD->getParent() << /*IsField*/true
5049 << Field << DiagKind << IsDtorCallInCtor;
5050 } else {
5051 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5052 S.Diag(Base->getLocStart(),
5053 diag::note_deleted_special_member_class_subobject)
5054 << CSM << MD->getParent() << /*IsField*/false
5055 << Base->getType() << DiagKind << IsDtorCallInCtor;
5056 }
5057
5058 if (DiagKind == 1)
5059 S.NoteDeletedFunction(Decl);
5060 // FIXME: Explain inaccessibility if DiagKind == 3.
5061 }
5062
5063 return true;
5064}
5065
Richard Smith921bd202012-02-26 09:11:52 +00005066/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005067/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005068bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005069 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005070 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005071 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005072
5073 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005074 // -- any direct or virtual base class, or non-static data member with no
5075 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005076 // either M has no default constructor or overload resolution as applied
5077 // to M's default constructor results in an ambiguity or in a function
5078 // that is deleted or inaccessible
5079 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5080 // -- a direct or virtual base class B that cannot be copied/moved because
5081 // overload resolution, as applied to B's corresponding special member,
5082 // results in an ambiguity or a function that is deleted or inaccessible
5083 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005084 // C++11 [class.dtor]p5:
5085 // -- any direct or virtual base class [...] has a type with a destructor
5086 // that is deleted or inaccessible
5087 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005088 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005089 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5090 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005091 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005092
Richard Smith852265f2012-03-30 20:53:28 +00005093 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5094 // -- any direct or virtual base class or non-static data member has a
5095 // type with a destructor that is deleted or inaccessible
5096 if (IsConstructor) {
5097 Sema::SpecialMemberOverloadResult *SMOR =
5098 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5099 false, false, false, false, false);
5100 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5101 return true;
5102 }
5103
Richard Smith921bd202012-02-26 09:11:52 +00005104 return false;
5105}
5106
5107/// Check whether we should delete a special member function due to the class
5108/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005109bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005110 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005111 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005112}
5113
5114/// Check whether we should delete a special member function due to the class
5115/// having a particular non-static data member.
5116bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5117 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5118 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5119
5120 if (CSM == Sema::CXXDefaultConstructor) {
5121 // For a default constructor, all references must be initialized in-class
5122 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005123 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5124 if (Diagnose)
5125 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5126 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005127 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005128 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005129 // C++11 [class.ctor]p5: any non-variant non-static data member of
5130 // const-qualified type (or array thereof) with no
5131 // brace-or-equal-initializer does not have a user-provided default
5132 // constructor.
5133 if (!inUnion() && FieldType.isConstQualified() &&
5134 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005135 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5136 if (Diagnose)
5137 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005138 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005139 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005140 }
5141
5142 if (inUnion() && !FieldType.isConstQualified())
5143 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005144 } else if (CSM == Sema::CXXCopyConstructor) {
5145 // For a copy constructor, data members must not be of rvalue reference
5146 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005147 if (FieldType->isRValueReferenceType()) {
5148 if (Diagnose)
5149 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5150 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005151 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005152 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005153 } else if (IsAssignment) {
5154 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005155 if (FieldType->isReferenceType()) {
5156 if (Diagnose)
5157 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5158 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005159 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005160 }
5161 if (!FieldRecord && FieldType.isConstQualified()) {
5162 // C++11 [class.copy]p23:
5163 // -- a non-static data member of const non-class type (or array thereof)
5164 if (Diagnose)
5165 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005166 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005167 return true;
5168 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005169 }
5170
5171 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005172 // Some additional restrictions exist on the variant members.
5173 if (!inUnion() && FieldRecord->isUnion() &&
5174 FieldRecord->isAnonymousStructOrUnion()) {
5175 bool AllVariantFieldsAreConst = true;
5176
Richard Smith5704fe82012-03-29 19:00:10 +00005177 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005178 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005179 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005180
5181 if (!UnionFieldType.isConstQualified())
5182 AllVariantFieldsAreConst = false;
5183
Richard Smith921bd202012-02-26 09:11:52 +00005184 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5185 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005186 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005187 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005188 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005189 }
5190
5191 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005192 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005193 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005194 if (Diagnose)
5195 S.Diag(FieldRecord->getLocation(),
5196 diag::note_deleted_default_ctor_all_const)
5197 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005198 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005199 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005200
Richard Smith5704fe82012-03-29 19:00:10 +00005201 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005202 // This is technically non-conformant, but sanity demands it.
5203 return false;
5204 }
5205
Richard Smithaf136f82012-07-18 03:51:16 +00005206 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5207 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005208 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005209 }
5210
5211 return false;
5212}
5213
5214/// C++11 [class.ctor] p5:
5215/// A defaulted default constructor for a class X is defined as deleted if
5216/// X is a union and all of its variant members are of const-qualified type.
5217bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005218 // This is a silly definition, because it gives an empty union a deleted
5219 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005220 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005221 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005222 if (Diagnose)
5223 S.Diag(MD->getParent()->getLocation(),
5224 diag::note_deleted_default_ctor_all_const)
5225 << MD->getParent() << /*not anonymous union*/0;
5226 return true;
5227 }
5228 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005229}
5230
5231/// Determine whether a defaulted special member function should be defined as
5232/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5233/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005234bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5235 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005236 if (MD->isInvalidDecl())
5237 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005238 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005239 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005240 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005241 return false;
5242
Richard Smithd951a1d2012-02-18 02:02:13 +00005243 // C++11 [expr.lambda.prim]p19:
5244 // The closure type associated with a lambda-expression has a
5245 // deleted (8.4.3) default constructor and a deleted copy
5246 // assignment operator.
5247 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005248 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5249 if (Diagnose)
5250 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005251 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005252 }
5253
Richard Smith6f1e2c62012-04-02 20:59:25 +00005254 // For an anonymous struct or union, the copy and assignment special members
5255 // will never be used, so skip the check. For an anonymous union declared at
5256 // namespace scope, the constructor and destructor are used.
5257 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5258 RD->isAnonymousStructOrUnion())
5259 return false;
5260
Richard Smith852265f2012-03-30 20:53:28 +00005261 // C++11 [class.copy]p7, p18:
5262 // If the class definition declares a move constructor or move assignment
5263 // operator, an implicitly declared copy constructor or copy assignment
5264 // operator is defined as deleted.
5265 if (MD->isImplicit() &&
5266 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5267 CXXMethodDecl *UserDeclaredMove = 0;
5268
5269 // In Microsoft mode, a user-declared move only causes the deletion of the
5270 // corresponding copy operation, not both copy operations.
5271 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005272 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005273 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005274
5275 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005276 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005277 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005278 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005279 break;
5280 }
5281 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005282 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005283 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005284 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005285 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005286
5287 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005288 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005289 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005290 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005291 break;
5292 }
5293 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005294 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005295 }
5296
5297 if (UserDeclaredMove) {
5298 Diag(UserDeclaredMove->getLocation(),
5299 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005300 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005301 << UserDeclaredMove->isMoveAssignmentOperator();
5302 return true;
5303 }
5304 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005305
Richard Smith6f1e2c62012-04-02 20:59:25 +00005306 // Do access control from the special member function
5307 ContextRAII MethodContext(*this, MD);
5308
Richard Smith921bd202012-02-26 09:11:52 +00005309 // C++11 [class.dtor]p5:
5310 // -- for a virtual destructor, lookup of the non-array deallocation function
5311 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005312 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005313 FunctionDecl *OperatorDelete = 0;
5314 DeclarationName Name =
5315 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5316 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005317 OperatorDelete, false)) {
5318 if (Diagnose)
5319 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005320 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005321 }
Richard Smith921bd202012-02-26 09:11:52 +00005322 }
5323
Richard Smith852265f2012-03-30 20:53:28 +00005324 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005325
Aaron Ballman574705e2014-03-13 15:41:46 +00005326 for (auto &BI : RD->bases())
5327 if (!BI.isVirtual() &&
5328 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005329 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005330
Richard Smithd1627032013-07-22 18:06:23 +00005331 // Per DR1611, do not consider virtual bases of constructors of abstract
5332 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005333 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005334 for (auto &BI : RD->vbases())
5335 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005336 return true;
5337 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005338
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005339 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005340 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005341 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005342 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005343
Richard Smithd951a1d2012-02-18 02:02:13 +00005344 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005345 return true;
5346
5347 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005348}
5349
Richard Smith92f241f2012-12-08 02:53:02 +00005350/// Perform lookup for a special member of the specified kind, and determine
5351/// whether it is trivial. If the triviality can be determined without the
5352/// lookup, skip it. This is intended for use when determining whether a
5353/// special member of a containing object is trivial, and thus does not ever
5354/// perform overload resolution for default constructors.
5355///
5356/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5357/// member that was most likely to be intended to be trivial, if any.
5358static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5359 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005360 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005361 if (Selected)
5362 *Selected = 0;
5363
5364 switch (CSM) {
5365 case Sema::CXXInvalid:
5366 llvm_unreachable("not a special member");
5367
5368 case Sema::CXXDefaultConstructor:
5369 // C++11 [class.ctor]p5:
5370 // A default constructor is trivial if:
5371 // - all the [direct subobjects] have trivial default constructors
5372 //
5373 // Note, no overload resolution is performed in this case.
5374 if (RD->hasTrivialDefaultConstructor())
5375 return true;
5376
5377 if (Selected) {
5378 // If there's a default constructor which could have been trivial, dig it
5379 // out. Otherwise, if there's any user-provided default constructor, point
5380 // to that as an example of why there's not a trivial one.
5381 CXXConstructorDecl *DefCtor = 0;
5382 if (RD->needsImplicitDefaultConstructor())
5383 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005384 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005385 if (!CI->isDefaultConstructor())
5386 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005387 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005388 if (!DefCtor->isUserProvided())
5389 break;
5390 }
5391
5392 *Selected = DefCtor;
5393 }
5394
5395 return false;
5396
5397 case Sema::CXXDestructor:
5398 // C++11 [class.dtor]p5:
5399 // A destructor is trivial if:
5400 // - all the direct [subobjects] have trivial destructors
5401 if (RD->hasTrivialDestructor())
5402 return true;
5403
5404 if (Selected) {
5405 if (RD->needsImplicitDestructor())
5406 S.DeclareImplicitDestructor(RD);
5407 *Selected = RD->getDestructor();
5408 }
5409
5410 return false;
5411
5412 case Sema::CXXCopyConstructor:
5413 // C++11 [class.copy]p12:
5414 // A copy constructor is trivial if:
5415 // - the constructor selected to copy each direct [subobject] is trivial
5416 if (RD->hasTrivialCopyConstructor()) {
5417 if (Quals == Qualifiers::Const)
5418 // We must either select the trivial copy constructor or reach an
5419 // ambiguity; no need to actually perform overload resolution.
5420 return true;
5421 } else if (!Selected) {
5422 return false;
5423 }
5424 // In C++98, we are not supposed to perform overload resolution here, but we
5425 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5426 // cases like B as having a non-trivial copy constructor:
5427 // struct A { template<typename T> A(T&); };
5428 // struct B { mutable A a; };
5429 goto NeedOverloadResolution;
5430
5431 case Sema::CXXCopyAssignment:
5432 // C++11 [class.copy]p25:
5433 // A copy assignment operator is trivial if:
5434 // - the assignment operator selected to copy each direct [subobject] is
5435 // trivial
5436 if (RD->hasTrivialCopyAssignment()) {
5437 if (Quals == Qualifiers::Const)
5438 return true;
5439 } else if (!Selected) {
5440 return false;
5441 }
5442 // In C++98, we are not supposed to perform overload resolution here, but we
5443 // treat that as a language defect.
5444 goto NeedOverloadResolution;
5445
5446 case Sema::CXXMoveConstructor:
5447 case Sema::CXXMoveAssignment:
5448 NeedOverloadResolution:
5449 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005450 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005451
5452 // The standard doesn't describe how to behave if the lookup is ambiguous.
5453 // We treat it as not making the member non-trivial, just like the standard
5454 // mandates for the default constructor. This should rarely matter, because
5455 // the member will also be deleted.
5456 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5457 return true;
5458
5459 if (!SMOR->getMethod()) {
5460 assert(SMOR->getKind() ==
5461 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5462 return false;
5463 }
5464
5465 // We deliberately don't check if we found a deleted special member. We're
5466 // not supposed to!
5467 if (Selected)
5468 *Selected = SMOR->getMethod();
5469 return SMOR->getMethod()->isTrivial();
5470 }
5471
5472 llvm_unreachable("unknown special method kind");
5473}
5474
Benjamin Kramer3e350262013-02-15 12:30:38 +00005475static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005476 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005477 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005478 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005479
5480 // Look for constructor templates.
5481 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5482 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5483 if (CXXConstructorDecl *CD =
5484 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5485 return CD;
5486 }
5487
5488 return 0;
5489}
5490
5491/// The kind of subobject we are checking for triviality. The values of this
5492/// enumeration are used in diagnostics.
5493enum TrivialSubobjectKind {
5494 /// The subobject is a base class.
5495 TSK_BaseClass,
5496 /// The subobject is a non-static data member.
5497 TSK_Field,
5498 /// The object is actually the complete object.
5499 TSK_CompleteObject
5500};
5501
5502/// Check whether the special member selected for a given type would be trivial.
5503static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005504 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005505 Sema::CXXSpecialMember CSM,
5506 TrivialSubobjectKind Kind,
5507 bool Diagnose) {
5508 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5509 if (!SubRD)
5510 return true;
5511
5512 CXXMethodDecl *Selected;
5513 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005514 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005515 return true;
5516
5517 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005518 if (ConstRHS)
5519 SubType.addConst();
5520
Richard Smith92f241f2012-12-08 02:53:02 +00005521 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5522 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5523 << Kind << SubType.getUnqualifiedType();
5524 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5525 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5526 } else if (!Selected)
5527 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5528 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5529 else if (Selected->isUserProvided()) {
5530 if (Kind == TSK_CompleteObject)
5531 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5532 << Kind << SubType.getUnqualifiedType() << CSM;
5533 else {
5534 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5535 << Kind << SubType.getUnqualifiedType() << CSM;
5536 S.Diag(Selected->getLocation(), diag::note_declared_at);
5537 }
5538 } else {
5539 if (Kind != TSK_CompleteObject)
5540 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5541 << Kind << SubType.getUnqualifiedType() << CSM;
5542
5543 // Explain why the defaulted or deleted special member isn't trivial.
5544 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5545 }
5546 }
5547
5548 return false;
5549}
5550
5551/// Check whether the members of a class type allow a special member to be
5552/// trivial.
5553static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5554 Sema::CXXSpecialMember CSM,
5555 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005556 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005557 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5558 continue;
5559
5560 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5561
5562 // Pretend anonymous struct or union members are members of this class.
5563 if (FI->isAnonymousStructOrUnion()) {
5564 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5565 CSM, ConstArg, Diagnose))
5566 return false;
5567 continue;
5568 }
5569
5570 // C++11 [class.ctor]p5:
5571 // A default constructor is trivial if [...]
5572 // -- no non-static data member of its class has a
5573 // brace-or-equal-initializer
5574 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5575 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005576 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005577 return false;
5578 }
5579
5580 // Objective C ARC 4.3.5:
5581 // [...] nontrivally ownership-qualified types are [...] not trivially
5582 // default constructible, copy constructible, move constructible, copy
5583 // assignable, move assignable, or destructible [...]
5584 if (S.getLangOpts().ObjCAutoRefCount &&
5585 FieldType.hasNonTrivialObjCLifetime()) {
5586 if (Diagnose)
5587 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5588 << RD << FieldType.getObjCLifetime();
5589 return false;
5590 }
5591
Richard Smith41c35d62013-11-27 03:39:20 +00005592 bool ConstRHS = ConstArg && !FI->isMutable();
5593 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5594 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005595 return false;
5596 }
5597
5598 return true;
5599}
5600
5601/// Diagnose why the specified class does not have a trivial special member of
5602/// the given kind.
5603void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5604 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005605
Richard Smith41c35d62013-11-27 03:39:20 +00005606 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5607 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005608 TSK_CompleteObject, /*Diagnose*/true);
5609}
5610
5611/// Determine whether a defaulted or deleted special member function is trivial,
5612/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5613/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5614bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5615 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005616 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5617
5618 CXXRecordDecl *RD = MD->getParent();
5619
5620 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005621
Richard Smith2002bfe2013-11-04 02:02:27 +00005622 // C++11 [class.copy]p12, p25: [DR1593]
5623 // A [special member] is trivial if [...] its parameter-type-list is
5624 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005625 switch (CSM) {
5626 case CXXDefaultConstructor:
5627 case CXXDestructor:
5628 // Trivial default constructors and destructors cannot have parameters.
5629 break;
5630
5631 case CXXCopyConstructor:
5632 case CXXCopyAssignment: {
5633 // Trivial copy operations always have const, non-volatile parameter types.
5634 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005635 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005636 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5637 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5638 if (Diagnose)
5639 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5640 << Param0->getSourceRange() << Param0->getType()
5641 << Context.getLValueReferenceType(
5642 Context.getRecordType(RD).withConst());
5643 return false;
5644 }
5645 break;
5646 }
5647
5648 case CXXMoveConstructor:
5649 case CXXMoveAssignment: {
5650 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005651 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005652 const RValueReferenceType *RT =
5653 Param0->getType()->getAs<RValueReferenceType>();
5654 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5655 if (Diagnose)
5656 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5657 << Param0->getSourceRange() << Param0->getType()
5658 << Context.getRValueReferenceType(Context.getRecordType(RD));
5659 return false;
5660 }
5661 break;
5662 }
5663
5664 case CXXInvalid:
5665 llvm_unreachable("not a special member");
5666 }
5667
Richard Smith92f241f2012-12-08 02:53:02 +00005668 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5669 if (Diagnose)
5670 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5671 diag::note_nontrivial_default_arg)
5672 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5673 return false;
5674 }
5675 if (MD->isVariadic()) {
5676 if (Diagnose)
5677 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5678 return false;
5679 }
5680
5681 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5682 // A copy/move [constructor or assignment operator] is trivial if
5683 // -- the [member] selected to copy/move each direct base class subobject
5684 // is trivial
5685 //
5686 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5687 // A [default constructor or destructor] is trivial if
5688 // -- all the direct base classes have trivial [default constructors or
5689 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005690 for (const auto &BI : RD->bases())
5691 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005692 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005693 return false;
5694
5695 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5696 // A copy/move [constructor or assignment operator] for a class X is
5697 // trivial if
5698 // -- for each non-static data member of X that is of class type (or array
5699 // thereof), the constructor selected to copy/move that member is
5700 // trivial
5701 //
5702 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5703 // A [default constructor or destructor] is trivial if
5704 // -- for all of the non-static data members of its class that are of class
5705 // type (or array thereof), each such class has a trivial [default
5706 // constructor or destructor]
5707 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5708 return false;
5709
5710 // C++11 [class.dtor]p5:
5711 // A destructor is trivial if [...]
5712 // -- the destructor is not virtual
5713 if (CSM == CXXDestructor && MD->isVirtual()) {
5714 if (Diagnose)
5715 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5716 return false;
5717 }
5718
5719 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5720 // A [special member] for class X is trivial if [...]
5721 // -- class X has no virtual functions and no virtual base classes
5722 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5723 if (!Diagnose)
5724 return false;
5725
5726 if (RD->getNumVBases()) {
5727 // Check for virtual bases. We already know that the corresponding
5728 // member in all bases is trivial, so vbases must all be direct.
5729 CXXBaseSpecifier &BS = *RD->vbases_begin();
5730 assert(BS.isVirtual());
5731 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5732 return false;
5733 }
5734
5735 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005736 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005737 if (MI->isVirtual()) {
5738 SourceLocation MLoc = MI->getLocStart();
5739 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5740 return false;
5741 }
5742 }
5743
5744 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5745 }
5746
5747 // Looks like it's trivial!
5748 return true;
5749}
5750
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005751/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005752namespace {
5753 struct FindHiddenVirtualMethodData {
5754 Sema *S;
5755 CXXMethodDecl *Method;
5756 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005757 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005758 };
5759}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005760
David Blaikie282c92a2012-10-19 00:53:08 +00005761/// \brief Check whether any most overriden method from MD in Methods
5762static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5763 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5764 if (MD->size_overridden_methods() == 0)
5765 return Methods.count(MD->getCanonicalDecl());
5766 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5767 E = MD->end_overridden_methods();
5768 I != E; ++I)
5769 if (CheckMostOverridenMethods(*I, Methods))
5770 return true;
5771 return false;
5772}
5773
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005774/// \brief Member lookup function that determines whether a given C++
5775/// method overloads virtual methods in a base class without overriding any,
5776/// to be used with CXXRecordDecl::lookupInBases().
5777static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5778 CXXBasePath &Path,
5779 void *UserData) {
5780 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5781
5782 FindHiddenVirtualMethodData &Data
5783 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5784
5785 DeclarationName Name = Data.Method->getDeclName();
5786 assert(Name.getNameKind() == DeclarationName::Identifier);
5787
5788 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005789 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005790 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005791 !Path.Decls.empty();
5792 Path.Decls = Path.Decls.slice(1)) {
5793 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005794 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005795 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005796 foundSameNameMethod = true;
5797 // Interested only in hidden virtual methods.
5798 if (!MD->isVirtual())
5799 continue;
5800 // If the method we are checking overrides a method from its base
5801 // don't warn about the other overloaded methods.
5802 if (!Data.S->IsOverload(Data.Method, MD, false))
5803 return true;
5804 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005805 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005806 overloadedMethods.push_back(MD);
5807 }
5808 }
5809
5810 if (foundSameNameMethod)
5811 Data.OverloadedMethods.append(overloadedMethods.begin(),
5812 overloadedMethods.end());
5813 return foundSameNameMethod;
5814}
5815
David Blaikie282c92a2012-10-19 00:53:08 +00005816/// \brief Add the most overriden methods from MD to Methods
5817static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5818 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5819 if (MD->size_overridden_methods() == 0)
5820 Methods.insert(MD->getCanonicalDecl());
5821 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5822 E = MD->end_overridden_methods();
5823 I != E; ++I)
5824 AddMostOverridenMethods(*I, Methods);
5825}
5826
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005827/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005828/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005829void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5830 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005831 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005832 return;
5833
5834 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5835 /*bool RecordPaths=*/false,
5836 /*bool DetectVirtual=*/false);
5837 FindHiddenVirtualMethodData Data;
5838 Data.Method = MD;
5839 Data.S = this;
5840
5841 // Keep the base methods that were overriden or introduced in the subclass
5842 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005843 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005844 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5845 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5846 NamedDecl *ND = *I;
5847 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005848 ND = shad->getTargetDecl();
5849 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5850 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005851 }
5852
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005853 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5854 OverloadedMethods = Data.OverloadedMethods;
5855}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005856
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005857void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5858 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5859 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5860 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5861 PartialDiagnostic PD = PDiag(
5862 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5863 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5864 Diag(overloadedMD->getLocation(), PD);
5865 }
5866}
5867
5868/// \brief Diagnose methods which overload virtual methods in a base class
5869/// without overriding any.
5870void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5871 if (MD->isInvalidDecl())
5872 return;
5873
5874 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5875 MD->getLocation()) == DiagnosticsEngine::Ignored)
5876 return;
5877
5878 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5879 FindHiddenVirtualMethods(MD, OverloadedMethods);
5880 if (!OverloadedMethods.empty()) {
5881 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5882 << MD << (OverloadedMethods.size() > 1);
5883
5884 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005885 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005886}
5887
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005888void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005889 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005890 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005891 SourceLocation RBrac,
5892 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005893 if (!TagDecl)
5894 return;
Mike Stump11289f42009-09-09 15:08:12 +00005895
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005896 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005897
Rafael Espindola06e1b132012-07-12 04:32:30 +00005898 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5899 if (l->getKind() != AttributeList::AT_Visibility)
5900 continue;
5901 l->setInvalid();
5902 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5903 l->getName();
5904 }
5905
David Blaikie751c5582011-09-22 02:58:26 +00005906 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005907 // strict aliasing violation!
5908 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005909 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005910
Douglas Gregor0be31a22010-07-02 17:43:08 +00005911 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005912 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005913}
5914
Douglas Gregor05379422008-11-03 17:51:48 +00005915/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5916/// special functions, such as the default constructor, copy
5917/// constructor, or destructor, to the given C++ class (C++
5918/// [special]p1). This routine can only be executed just before the
5919/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005920void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005921 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005922 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005923
Richard Smith6b02d462012-12-08 08:32:28 +00005924 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005925 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005926
Richard Smith6b02d462012-12-08 08:32:28 +00005927 // If the properties or semantics of the copy constructor couldn't be
5928 // determined while the class was being declared, force a declaration
5929 // of it now.
5930 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5931 DeclareImplicitCopyConstructor(ClassDecl);
5932 }
5933
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005934 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005935 ++ASTContext::NumImplicitMoveConstructors;
5936
Richard Smith6b02d462012-12-08 08:32:28 +00005937 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5938 DeclareImplicitMoveConstructor(ClassDecl);
5939 }
5940
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005941 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5942 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005943
5944 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005945 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005946 // it shows up in the right place in the vtable and that we diagnose
5947 // problems with the implicit exception specification.
5948 if (ClassDecl->isDynamicClass() ||
5949 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005950 DeclareImplicitCopyAssignment(ClassDecl);
5951 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005952
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005953 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005954 ++ASTContext::NumImplicitMoveAssignmentOperators;
5955
5956 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005957 if (ClassDecl->isDynamicClass() ||
5958 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005959 DeclareImplicitMoveAssignment(ClassDecl);
5960 }
5961
Douglas Gregor7454c562010-07-02 20:37:36 +00005962 if (!ClassDecl->hasUserDeclaredDestructor()) {
5963 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005964
5965 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005966 // have to declare the destructor immediately. This ensures that, e.g., it
5967 // shows up in the right place in the vtable and that we diagnose problems
5968 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005969 if (ClassDecl->isDynamicClass() ||
5970 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005971 DeclareImplicitDestructor(ClassDecl);
5972 }
Douglas Gregor05379422008-11-03 17:51:48 +00005973}
5974
Francois Pichet1c229c02011-04-22 22:18:13 +00005975void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5976 if (!D)
5977 return;
5978
5979 int NumParamList = D->getNumTemplateParameterLists();
5980 for (int i = 0; i < NumParamList; i++) {
5981 TemplateParameterList* Params = D->getTemplateParameterList(i);
5982 for (TemplateParameterList::iterator Param = Params->begin(),
5983 ParamEnd = Params->end();
5984 Param != ParamEnd; ++Param) {
5985 NamedDecl *Named = cast<NamedDecl>(*Param);
5986 if (Named->getDeclName()) {
5987 S->AddDecl(Named);
5988 IdResolver.AddDecl(Named);
5989 }
5990 }
5991 }
5992}
5993
John McCall48871652010-08-21 09:40:31 +00005994void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005995 if (!D)
5996 return;
5997
5998 TemplateParameterList *Params = 0;
5999 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6000 Params = Template->getTemplateParameters();
6001 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6002 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6003 Params = PartialSpec->getTemplateParameters();
6004 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006005 return;
6006
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006007 for (TemplateParameterList::iterator Param = Params->begin(),
6008 ParamEnd = Params->end();
6009 Param != ParamEnd; ++Param) {
6010 NamedDecl *Named = cast<NamedDecl>(*Param);
6011 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006012 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006013 IdResolver.AddDecl(Named);
6014 }
6015 }
6016}
6017
John McCall48871652010-08-21 09:40:31 +00006018void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006019 if (!RecordD) return;
6020 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006021 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006022 PushDeclContext(S, Record);
6023}
6024
John McCall48871652010-08-21 09:40:31 +00006025void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006026 if (!RecordD) return;
6027 PopDeclContext();
6028}
6029
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006030/// This is used to implement the constant expression evaluation part of the
6031/// attribute enable_if extension. There is nothing in standard C++ which would
6032/// require reentering parameters.
6033void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6034 if (!Param)
6035 return;
6036
6037 S->AddDecl(Param);
6038 if (Param->getDeclName())
6039 IdResolver.AddDecl(Param);
6040}
6041
Douglas Gregor4d87df52008-12-16 21:30:33 +00006042/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6043/// parsing a top-level (non-nested) C++ class, and we are now
6044/// parsing those parts of the given Method declaration that could
6045/// not be parsed earlier (C++ [class.mem]p2), such as default
6046/// arguments. This action should enter the scope of the given
6047/// Method declaration as if we had just parsed the qualified method
6048/// name. However, it should not bring the parameters into scope;
6049/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006050void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006051}
6052
6053/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6054/// C++ method declaration. We're (re-)introducing the given
6055/// function parameter into scope for use in parsing later parts of
6056/// the method declaration. For example, we could see an
6057/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006058void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006059 if (!ParamD)
6060 return;
Mike Stump11289f42009-09-09 15:08:12 +00006061
John McCall48871652010-08-21 09:40:31 +00006062 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006063
6064 // If this parameter has an unparsed default argument, clear it out
6065 // to make way for the parsed default argument.
6066 if (Param->hasUnparsedDefaultArg())
6067 Param->setDefaultArg(0);
6068
John McCall48871652010-08-21 09:40:31 +00006069 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006070 if (Param->getDeclName())
6071 IdResolver.AddDecl(Param);
6072}
6073
6074/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6075/// processing the delayed method declaration for Method. The method
6076/// declaration is now considered finished. There may be a separate
6077/// ActOnStartOfFunctionDef action later (not necessarily
6078/// immediately!) for this method, if it was also defined inside the
6079/// class body.
John McCall48871652010-08-21 09:40:31 +00006080void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006081 if (!MethodD)
6082 return;
Mike Stump11289f42009-09-09 15:08:12 +00006083
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006084 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006085
John McCall48871652010-08-21 09:40:31 +00006086 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006087
6088 // Now that we have our default arguments, check the constructor
6089 // again. It could produce additional diagnostics or affect whether
6090 // the class has implicitly-declared destructors, among other
6091 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006092 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6093 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006094
6095 // Check the default arguments, which we may have added.
6096 if (!Method->isInvalidDecl())
6097 CheckCXXDefaultArguments(Method);
6098}
6099
Douglas Gregor831c93f2008-11-05 20:51:48 +00006100/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006101/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006102/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006103/// emit diagnostics and set the invalid bit to true. In any case, the type
6104/// will be updated to reflect a well-formed type for the constructor and
6105/// returned.
6106QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006107 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006108 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006109
6110 // C++ [class.ctor]p3:
6111 // A constructor shall not be virtual (10.3) or static (9.4). A
6112 // constructor can be invoked for a const, volatile or const
6113 // volatile object. A constructor shall not be declared const,
6114 // volatile, or const volatile (9.3.2).
6115 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006116 if (!D.isInvalidType())
6117 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6118 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6119 << SourceRange(D.getIdentifierLoc());
6120 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006121 }
John McCall8e7d6562010-08-26 03:08:43 +00006122 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006123 if (!D.isInvalidType())
6124 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6125 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6126 << SourceRange(D.getIdentifierLoc());
6127 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006128 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006129 }
Mike Stump11289f42009-09-09 15:08:12 +00006130
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006131 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006132 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006133 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006134 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6135 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006136 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006137 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6138 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006139 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006140 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6141 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006142 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006143 }
Mike Stump11289f42009-09-09 15:08:12 +00006144
Douglas Gregordb9d6642011-01-26 05:01:58 +00006145 // C++0x [class.ctor]p4:
6146 // A constructor shall not be declared with a ref-qualifier.
6147 if (FTI.hasRefQualifier()) {
6148 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6149 << FTI.RefQualifierIsLValueRef
6150 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6151 D.setInvalidType();
6152 }
6153
Douglas Gregor831c93f2008-11-05 20:51:48 +00006154 // Rebuild the function type "R" without any type qualifiers (in
6155 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006156 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006157 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006158 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006159 return R;
6160
6161 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6162 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006163 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006164
6165 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006166}
6167
Douglas Gregor4d87df52008-12-16 21:30:33 +00006168/// CheckConstructor - Checks a fully-formed constructor for
6169/// well-formedness, issuing any diagnostics required. Returns true if
6170/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006171void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006172 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006173 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6174 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006175 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006176
6177 // C++ [class.copy]p3:
6178 // A declaration of a constructor for a class X is ill-formed if
6179 // its first parameter is of type (optionally cv-qualified) X and
6180 // either there are no other parameters or else all other
6181 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006182 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006183 ((Constructor->getNumParams() == 1) ||
6184 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006185 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6186 Constructor->getTemplateSpecializationKind()
6187 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006188 QualType ParamType = Constructor->getParamDecl(0)->getType();
6189 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6190 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006191 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006192 const char *ConstRef
6193 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6194 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006195 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006196 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006197
6198 // FIXME: Rather that making the constructor invalid, we should endeavor
6199 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006200 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006201 }
6202 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006203}
6204
John McCalldeb646e2010-08-04 01:04:25 +00006205/// CheckDestructor - Checks a fully-formed destructor definition for
6206/// well-formedness, issuing any diagnostics required. Returns true
6207/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006208bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006209 CXXRecordDecl *RD = Destructor->getParent();
6210
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006211 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006212 SourceLocation Loc;
6213
6214 if (!Destructor->isImplicit())
6215 Loc = Destructor->getLocation();
6216 else
6217 Loc = RD->getLocation();
6218
6219 // If we have a virtual destructor, look up the deallocation function
6220 FunctionDecl *OperatorDelete = 0;
6221 DeclarationName Name =
6222 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006223 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006224 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006225 // If there's no class-specific operator delete, look up the global
6226 // non-array delete.
6227 if (!OperatorDelete)
6228 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006229
Eli Friedmanfa0df832012-02-02 03:46:19 +00006230 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006231
6232 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006233 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006234
6235 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006236}
6237
Mike Stump11289f42009-09-09 15:08:12 +00006238static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006239FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006240 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6241 FTI.Params[0].Param &&
6242 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006243}
6244
Douglas Gregor831c93f2008-11-05 20:51:48 +00006245/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6246/// the well-formednes of the destructor declarator @p D with type @p
6247/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006248/// emit diagnostics and set the declarator to invalid. Even if this happens,
6249/// will be updated to reflect a well-formed type for the destructor and
6250/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006251QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006252 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006253 // C++ [class.dtor]p1:
6254 // [...] A typedef-name that names a class is a class-name
6255 // (7.1.3); however, a typedef-name that names a class shall not
6256 // be used as the identifier in the declarator for a destructor
6257 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006258 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006259 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006260 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006261 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006262 else if (const TemplateSpecializationType *TST =
6263 DeclaratorType->getAs<TemplateSpecializationType>())
6264 if (TST->isTypeAlias())
6265 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6266 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006267
6268 // C++ [class.dtor]p2:
6269 // A destructor is used to destroy objects of its class type. A
6270 // destructor takes no parameters, and no return type can be
6271 // specified for it (not even void). The address of a destructor
6272 // shall not be taken. A destructor shall not be static. A
6273 // destructor can be invoked for a const, volatile or const
6274 // volatile object. A destructor shall not be declared const,
6275 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006276 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006277 if (!D.isInvalidType())
6278 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6279 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006280 << SourceRange(D.getIdentifierLoc())
6281 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6282
John McCall8e7d6562010-08-26 03:08:43 +00006283 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006284 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006285 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006286 // Destructors don't have return types, but the parser will
6287 // happily parse something like:
6288 //
6289 // class X {
6290 // float ~X();
6291 // };
6292 //
6293 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006294 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6295 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6296 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006297 }
Mike Stump11289f42009-09-09 15:08:12 +00006298
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006299 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006300 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006301 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006302 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6303 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006304 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006305 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6306 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006307 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006308 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6309 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006310 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006311 }
6312
Douglas Gregordb9d6642011-01-26 05:01:58 +00006313 // C++0x [class.dtor]p2:
6314 // A destructor shall not be declared with a ref-qualifier.
6315 if (FTI.hasRefQualifier()) {
6316 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6317 << FTI.RefQualifierIsLValueRef
6318 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6319 D.setInvalidType();
6320 }
6321
Douglas Gregor831c93f2008-11-05 20:51:48 +00006322 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006323 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006324 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6325
6326 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006327 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006328 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006329 }
6330
Mike Stump11289f42009-09-09 15:08:12 +00006331 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006332 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006333 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006334 D.setInvalidType();
6335 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006336
6337 // Rebuild the function type "R" without any type qualifiers or
6338 // parameters (in case any of the errors above fired) and with
6339 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006340 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006341 if (!D.isInvalidType())
6342 return R;
6343
Douglas Gregor95755162010-07-01 05:10:53 +00006344 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006345 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6346 EPI.Variadic = false;
6347 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006348 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006349 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006350}
6351
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006352/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6353/// well-formednes of the conversion function declarator @p D with
6354/// type @p R. If there are any errors in the declarator, this routine
6355/// will emit diagnostics and return true. Otherwise, it will return
6356/// false. Either way, the type @p R will be updated to reflect a
6357/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006358void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006359 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006360 // C++ [class.conv.fct]p1:
6361 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006362 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006363 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006364 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006365 if (!D.isInvalidType())
6366 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006367 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6368 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006369 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006370 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006371 }
John McCall212fa2e2010-04-13 00:04:31 +00006372
6373 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6374
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006375 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006376 // Conversion functions don't have return types, but the parser will
6377 // happily parse something like:
6378 //
6379 // class X {
6380 // float operator bool();
6381 // };
6382 //
6383 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006384 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6385 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6386 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006387 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006388 }
6389
John McCall212fa2e2010-04-13 00:04:31 +00006390 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6391
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006392 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006393 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006394 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6395
6396 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006397 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006398 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006399 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006400 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006401 D.setInvalidType();
6402 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006403
John McCall212fa2e2010-04-13 00:04:31 +00006404 // Diagnose "&operator bool()" and other such nonsense. This
6405 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006406 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006407 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006408 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006409 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006410 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006411 }
6412
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006413 // C++ [class.conv.fct]p4:
6414 // The conversion-type-id shall not represent a function type nor
6415 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006416 if (ConvType->isArrayType()) {
6417 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6418 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006419 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006420 } else if (ConvType->isFunctionType()) {
6421 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6422 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006423 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006424 }
6425
6426 // Rebuild the function type "R" without any parameters (in case any
6427 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006428 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006429 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006430 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006431
Douglas Gregor5fb53972009-01-14 15:45:31 +00006432 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006433 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006434 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006435 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006436 diag::warn_cxx98_compat_explicit_conversion_functions :
6437 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006438 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006439}
6440
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006441/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6442/// the declaration of the given C++ conversion function. This routine
6443/// is responsible for recording the conversion function in the C++
6444/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006445Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006446 assert(Conversion && "Expected to receive a conversion function declaration");
6447
Douglas Gregor4287b372008-12-12 08:25:50 +00006448 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006449
6450 // Make sure we aren't redeclaring the conversion function.
6451 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006452
6453 // C++ [class.conv.fct]p1:
6454 // [...] A conversion function is never used to convert a
6455 // (possibly cv-qualified) object to the (possibly cv-qualified)
6456 // same object type (or a reference to it), to a (possibly
6457 // cv-qualified) base class of that type (or a reference to it),
6458 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006459 // FIXME: Suppress this warning if the conversion function ends up being a
6460 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006461 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006462 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006463 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006464 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006465 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6466 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006467 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006468 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006469 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6470 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006471 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006472 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006473 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006474 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006475 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006476 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006477 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006478 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479 }
6480
Douglas Gregor457104e2010-09-29 04:25:11 +00006481 if (FunctionTemplateDecl *ConversionTemplate
6482 = Conversion->getDescribedFunctionTemplate())
6483 return ConversionTemplate;
6484
John McCall48871652010-08-21 09:40:31 +00006485 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006486}
6487
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006488//===----------------------------------------------------------------------===//
6489// Namespace Handling
6490//===----------------------------------------------------------------------===//
6491
Richard Smith45bb8852012-10-04 22:13:39 +00006492/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6493/// reopened.
6494static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6495 SourceLocation Loc,
6496 IdentifierInfo *II, bool *IsInline,
6497 NamespaceDecl *PrevNS) {
6498 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006499
Richard Smithf501cc32012-10-05 01:46:25 +00006500 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6501 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6502 // inline namespaces, with the intention of bringing names into namespace std.
6503 //
6504 // We support this just well enough to get that case working; this is not
6505 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006506 if (*IsInline && II && II->getName().startswith("__atomic") &&
6507 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006508 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006509 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6510 NS = NS->getPreviousDecl())
6511 NS->setInline(*IsInline);
6512 // Patch up the lookup table for the containing namespace. This isn't really
6513 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006514 for (auto *I : PrevNS->decls())
6515 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006516 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6517 return;
6518 }
6519
6520 if (PrevNS->isInline())
6521 // The user probably just forgot the 'inline', so suggest that it
6522 // be added back.
6523 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6524 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6525 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006526 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006527
6528 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6529 *IsInline = PrevNS->isInline();
6530}
John McCallb1be5232010-08-26 09:15:37 +00006531
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006532/// ActOnStartNamespaceDef - This is called at the start of a namespace
6533/// definition.
John McCall48871652010-08-21 09:40:31 +00006534Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006535 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006536 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006537 SourceLocation IdentLoc,
6538 IdentifierInfo *II,
6539 SourceLocation LBrace,
6540 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006541 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6542 // For anonymous namespace, take the location of the left brace.
6543 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006544 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006545 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006546 bool IsStd = false;
6547 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006548 Scope *DeclRegionScope = NamespcScope->getParent();
6549
Douglas Gregore57e7522012-01-07 09:11:48 +00006550 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006551 if (II) {
6552 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006553 // The identifier in an original-namespace-definition shall not
6554 // have been previously defined in the declarative region in
6555 // which the original-namespace-definition appears. The
6556 // identifier in an original-namespace-definition is the name of
6557 // the namespace. Subsequently in that declarative region, it is
6558 // treated as an original-namespace-name.
6559 //
6560 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006561 // look through using directives, just look for any ordinary names.
6562
6563 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006564 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6565 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006566 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006567 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6568 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6569 ++I) {
6570 if ((*I)->getIdentifierNamespace() & IDNS) {
6571 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006572 break;
6573 }
6574 }
6575
Douglas Gregore57e7522012-01-07 09:11:48 +00006576 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6577
6578 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006579 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006580 if (IsInline != PrevNS->isInline())
6581 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6582 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006583 } else if (PrevDecl) {
6584 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006585 Diag(Loc, diag::err_redefinition_different_kind)
6586 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006587 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006588 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006589 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006590 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006591 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006592 // This is the first "real" definition of the namespace "std", so update
6593 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006594 PrevNS = getStdNamespace();
6595 IsStd = true;
6596 AddToKnown = !IsInline;
6597 } else {
6598 // We've seen this namespace for the first time.
6599 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006600 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006601 } else {
John McCall4fa53422009-10-01 00:25:31 +00006602 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006603
6604 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006605 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006606 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006607 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006608 } else {
6609 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006610 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006611 }
6612
Richard Smith45bb8852012-10-04 22:13:39 +00006613 if (PrevNS && IsInline != PrevNS->isInline())
6614 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6615 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006616 }
6617
6618 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6619 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006620 if (IsInvalid)
6621 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006622
6623 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006624
Douglas Gregore57e7522012-01-07 09:11:48 +00006625 // FIXME: Should we be merging attributes?
6626 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006627 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006628
6629 if (IsStd)
6630 StdNamespace = Namespc;
6631 if (AddToKnown)
6632 KnownNamespaces[Namespc] = false;
6633
6634 if (II) {
6635 PushOnScopeChains(Namespc, DeclRegionScope);
6636 } else {
6637 // Link the anonymous namespace into its parent.
6638 DeclContext *Parent = CurContext->getRedeclContext();
6639 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6640 TU->setAnonymousNamespace(Namespc);
6641 } else {
6642 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006643 }
John McCall4fa53422009-10-01 00:25:31 +00006644
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006645 CurContext->addDecl(Namespc);
6646
John McCall4fa53422009-10-01 00:25:31 +00006647 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6648 // behaves as if it were replaced by
6649 // namespace unique { /* empty body */ }
6650 // using namespace unique;
6651 // namespace unique { namespace-body }
6652 // where all occurrences of 'unique' in a translation unit are
6653 // replaced by the same identifier and this identifier differs
6654 // from all other identifiers in the entire program.
6655
6656 // We just create the namespace with an empty name and then add an
6657 // implicit using declaration, just like the standard suggests.
6658 //
6659 // CodeGen enforces the "universally unique" aspect by giving all
6660 // declarations semantically contained within an anonymous
6661 // namespace internal linkage.
6662
Douglas Gregore57e7522012-01-07 09:11:48 +00006663 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006664 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006665 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006666 /* 'using' */ LBrace,
6667 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006668 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006669 /* identifier */ SourceLocation(),
6670 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006671 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006672 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006673 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006674 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006675 }
6676
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006677 ActOnDocumentableDecl(Namespc);
6678
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006679 // Although we could have an invalid decl (i.e. the namespace name is a
6680 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006681 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6682 // for the namespace has the declarations that showed up in that particular
6683 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006684 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006685 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006686}
6687
Sebastian Redla6602e92009-11-23 15:34:23 +00006688/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6689/// is a namespace alias, returns the namespace it points to.
6690static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6691 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6692 return AD->getNamespace();
6693 return dyn_cast_or_null<NamespaceDecl>(D);
6694}
6695
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006696/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6697/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006698void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006699 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6700 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006701 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006702 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006703 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006704 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006705}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006706
John McCall28a0cf72010-08-25 07:42:41 +00006707CXXRecordDecl *Sema::getStdBadAlloc() const {
6708 return cast_or_null<CXXRecordDecl>(
6709 StdBadAlloc.get(Context.getExternalSource()));
6710}
6711
6712NamespaceDecl *Sema::getStdNamespace() const {
6713 return cast_or_null<NamespaceDecl>(
6714 StdNamespace.get(Context.getExternalSource()));
6715}
6716
Douglas Gregorcdf87022010-06-29 17:53:46 +00006717/// \brief Retrieve the special "std" namespace, which may require us to
6718/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006719NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006720 if (!StdNamespace) {
6721 // The "std" namespace has not yet been defined, so build one implicitly.
6722 StdNamespace = NamespaceDecl::Create(Context,
6723 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006724 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006725 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006726 &PP.getIdentifierTable().get("std"),
6727 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006728 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006729 }
6730
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006731 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006732}
6733
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006734bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006735 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006736 "Looking for std::initializer_list outside of C++.");
6737
6738 // We're looking for implicit instantiations of
6739 // template <typename E> class std::initializer_list.
6740
6741 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6742 return false;
6743
Sebastian Redl43144e72012-01-17 22:49:58 +00006744 ClassTemplateDecl *Template = 0;
6745 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006746
Sebastian Redl43144e72012-01-17 22:49:58 +00006747 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006748
Sebastian Redl43144e72012-01-17 22:49:58 +00006749 ClassTemplateSpecializationDecl *Specialization =
6750 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6751 if (!Specialization)
6752 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006753
Sebastian Redl43144e72012-01-17 22:49:58 +00006754 Template = Specialization->getSpecializedTemplate();
6755 Arguments = Specialization->getTemplateArgs().data();
6756 } else if (const TemplateSpecializationType *TST =
6757 Ty->getAs<TemplateSpecializationType>()) {
6758 Template = dyn_cast_or_null<ClassTemplateDecl>(
6759 TST->getTemplateName().getAsTemplateDecl());
6760 Arguments = TST->getArgs();
6761 }
6762 if (!Template)
6763 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006764
6765 if (!StdInitializerList) {
6766 // Haven't recognized std::initializer_list yet, maybe this is it.
6767 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6768 if (TemplateClass->getIdentifier() !=
6769 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006770 !getStdNamespace()->InEnclosingNamespaceSetOf(
6771 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006772 return false;
6773 // This is a template called std::initializer_list, but is it the right
6774 // template?
6775 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006776 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006777 return false;
6778 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6779 return false;
6780
6781 // It's the right template.
6782 StdInitializerList = Template;
6783 }
6784
6785 if (Template != StdInitializerList)
6786 return false;
6787
6788 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006789 if (Element)
6790 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006791 return true;
6792}
6793
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006794static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6795 NamespaceDecl *Std = S.getStdNamespace();
6796 if (!Std) {
6797 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6798 return 0;
6799 }
6800
6801 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6802 Loc, Sema::LookupOrdinaryName);
6803 if (!S.LookupQualifiedName(Result, Std)) {
6804 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6805 return 0;
6806 }
6807 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6808 if (!Template) {
6809 Result.suppressDiagnostics();
6810 // We found something weird. Complain about the first thing we found.
6811 NamedDecl *Found = *Result.begin();
6812 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6813 return 0;
6814 }
6815
6816 // We found some template called std::initializer_list. Now verify that it's
6817 // correct.
6818 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006819 if (Params->getMinRequiredArguments() != 1 ||
6820 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006821 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6822 return 0;
6823 }
6824
6825 return Template;
6826}
6827
6828QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6829 if (!StdInitializerList) {
6830 StdInitializerList = LookupStdInitializerList(*this, Loc);
6831 if (!StdInitializerList)
6832 return QualType();
6833 }
6834
6835 TemplateArgumentListInfo Args(Loc, Loc);
6836 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6837 Context.getTrivialTypeSourceInfo(Element,
6838 Loc)));
6839 return Context.getCanonicalType(
6840 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6841}
6842
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006843bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6844 // C++ [dcl.init.list]p2:
6845 // A constructor is an initializer-list constructor if its first parameter
6846 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6847 // std::initializer_list<E> for some type E, and either there are no other
6848 // parameters or else all other parameters have default arguments.
6849 if (Ctor->getNumParams() < 1 ||
6850 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6851 return false;
6852
6853 QualType ArgType = Ctor->getParamDecl(0)->getType();
6854 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6855 ArgType = RT->getPointeeType().getUnqualifiedType();
6856
6857 return isStdInitializerList(ArgType, 0);
6858}
6859
Douglas Gregora172e082011-03-26 22:25:30 +00006860/// \brief Determine whether a using statement is in a context where it will be
6861/// apply in all contexts.
6862static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6863 switch (CurContext->getDeclKind()) {
6864 case Decl::TranslationUnit:
6865 return true;
6866 case Decl::LinkageSpec:
6867 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6868 default:
6869 return false;
6870 }
6871}
6872
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006873namespace {
6874
6875// Callback to only accept typo corrections that are namespaces.
6876class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006877public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006878 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006879 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006880 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006881 return false;
6882 }
6883};
6884
6885}
6886
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006887static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6888 CXXScopeSpec &SS,
6889 SourceLocation IdentLoc,
6890 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006891 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006892 R.clear();
6893 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006894 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006895 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006896 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006897 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6898 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006899 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006900 S.diagnoseTypo(Corrected,
6901 S.PDiag(diag::err_using_directive_member_suggest)
6902 << Ident << DC << DroppedSpecifier << SS.getRange(),
6903 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006904 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006905 S.diagnoseTypo(Corrected,
6906 S.PDiag(diag::err_using_directive_suggest) << Ident,
6907 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006908 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006909 R.addDecl(Corrected.getCorrectionDecl());
6910 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006911 }
6912 return false;
6913}
6914
John McCall48871652010-08-21 09:40:31 +00006915Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006916 SourceLocation UsingLoc,
6917 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006918 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006919 SourceLocation IdentLoc,
6920 IdentifierInfo *NamespcName,
6921 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006922 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6923 assert(NamespcName && "Invalid NamespcName.");
6924 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006925
6926 // This can only happen along a recovery path.
6927 while (S->getFlags() & Scope::TemplateParamScope)
6928 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006929 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006930
Douglas Gregor889ceb72009-02-03 19:21:40 +00006931 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006932 NestedNameSpecifier *Qualifier = 0;
6933 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006934 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006935
Douglas Gregor34074322009-01-14 22:20:51 +00006936 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006937 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6938 LookupParsedName(R, S, &SS);
6939 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006940 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006941
Douglas Gregorcdf87022010-06-29 17:53:46 +00006942 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006943 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006944 // Allow "using namespace std;" or "using namespace ::std;" even if
6945 // "std" hasn't been defined yet, for GCC compatibility.
6946 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6947 NamespcName->isStr("std")) {
6948 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006949 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006950 R.resolveKind();
6951 }
6952 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006953 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006954 }
6955
John McCall9f3059a2009-10-09 21:13:30 +00006956 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006957 NamedDecl *Named = R.getFoundDecl();
6958 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6959 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006960 // C++ [namespace.udir]p1:
6961 // A using-directive specifies that the names in the nominated
6962 // namespace can be used in the scope in which the
6963 // using-directive appears after the using-directive. During
6964 // unqualified name lookup (3.4.1), the names appear as if they
6965 // were declared in the nearest enclosing namespace which
6966 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006967 // namespace. [Note: in this context, "contains" means "contains
6968 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006969
6970 // Find enclosing context containing both using-directive and
6971 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006972 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006973 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6974 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6975 CommonAncestor = CommonAncestor->getParent();
6976
Sebastian Redla6602e92009-11-23 15:34:23 +00006977 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006978 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006979 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006980
Douglas Gregora172e082011-03-26 22:25:30 +00006981 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006982 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006983 Diag(IdentLoc, diag::warn_using_directive_in_header);
6984 }
6985
Douglas Gregor889ceb72009-02-03 19:21:40 +00006986 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006987 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006988 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006989 }
6990
Richard Smith54ecd982013-02-20 19:22:51 +00006991 if (UDir)
6992 ProcessDeclAttributeList(S, UDir, AttrList);
6993
John McCall48871652010-08-21 09:40:31 +00006994 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006995}
6996
6997void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006998 // If the scope has an associated entity and the using directive is at
6999 // namespace or translation unit scope, add the UsingDirectiveDecl into
7000 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007001 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007002 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007003 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007004 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007005 // Otherwise, it is at block sope. The using-directives will affect lookup
7006 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007007 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007008}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007009
Douglas Gregorfec52632009-06-20 00:51:54 +00007010
John McCall48871652010-08-21 09:40:31 +00007011Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007012 AccessSpecifier AS,
7013 bool HasUsingKeyword,
7014 SourceLocation UsingLoc,
7015 CXXScopeSpec &SS,
7016 UnqualifiedId &Name,
7017 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007018 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007019 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007020 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007021
Douglas Gregor220f4272009-11-04 16:30:06 +00007022 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007023 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007024 case UnqualifiedId::IK_Identifier:
7025 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007026 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007027 case UnqualifiedId::IK_ConversionFunctionId:
7028 break;
7029
7030 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007031 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007032 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007033 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007034 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007035 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007036 diag::err_using_decl_constructor)
7037 << SS.getRange();
7038
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007039 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007040
John McCall48871652010-08-21 09:40:31 +00007041 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007042
7043 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007044 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007045 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007046 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007047
7048 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007049 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007050 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007051 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007052 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007053
7054 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7055 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007056 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007057 return 0;
John McCall3969e302009-12-08 07:46:18 +00007058
Richard Smithc2bc61b2013-03-18 21:12:30 +00007059 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007060 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007061 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007062 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7063 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007064 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007065 }
7066
Douglas Gregorc4356532010-12-16 00:46:58 +00007067 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7068 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7069 return 0;
7070
John McCall3f746822009-11-17 05:59:44 +00007071 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007072 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007073 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007074 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007075 if (UD)
7076 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007077
John McCall48871652010-08-21 09:40:31 +00007078 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007079}
7080
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007081/// \brief Determine whether a using declaration considers the given
7082/// declarations as "equivalent", e.g., if they are redeclarations of
7083/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007084static bool
7085IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7086 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007087 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007088
Richard Smithdda56e42011-04-15 14:24:37 +00007089 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007090 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007091 return Context.hasSameType(TD1->getUnderlyingType(),
7092 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007093
7094 return false;
7095}
7096
7097
John McCall84d87672009-12-10 09:41:52 +00007098/// Determines whether to create a using shadow decl for a particular
7099/// decl, given the set of decls existing prior to this using lookup.
7100bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007101 const LookupResult &Previous,
7102 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007103 // Diagnose finding a decl which is not from a base class of the
7104 // current class. We do this now because there are cases where this
7105 // function will silently decide not to build a shadow decl, which
7106 // will pre-empt further diagnostics.
7107 //
7108 // We don't need to do this in C++0x because we do the check once on
7109 // the qualifier.
7110 //
7111 // FIXME: diagnose the following if we care enough:
7112 // struct A { int foo; };
7113 // struct B : A { using A::foo; };
7114 // template <class T> struct C : A {};
7115 // template <class T> struct D : C<T> { using B::foo; } // <---
7116 // This is invalid (during instantiation) in C++03 because B::foo
7117 // resolves to the using decl in B, which is not a base class of D<T>.
7118 // We can't diagnose it immediately because C<T> is an unknown
7119 // specialization. The UsingShadowDecl in D<T> then points directly
7120 // to A::foo, which will look well-formed when we instantiate.
7121 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007122 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007123 DeclContext *OrigDC = Orig->getDeclContext();
7124
7125 // Handle enums and anonymous structs.
7126 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7127 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7128 while (OrigRec->isAnonymousStructOrUnion())
7129 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7130
7131 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7132 if (OrigDC == CurContext) {
7133 Diag(Using->getLocation(),
7134 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007135 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007136 Diag(Orig->getLocation(), diag::note_using_decl_target);
7137 return true;
7138 }
7139
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007140 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007141 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007142 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007143 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007144 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007145 Diag(Orig->getLocation(), diag::note_using_decl_target);
7146 return true;
7147 }
7148 }
7149
7150 if (Previous.empty()) return false;
7151
7152 NamedDecl *Target = Orig;
7153 if (isa<UsingShadowDecl>(Target))
7154 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7155
John McCalla17e83e2009-12-11 02:33:26 +00007156 // If the target happens to be one of the previous declarations, we
7157 // don't have a conflict.
7158 //
7159 // FIXME: but we might be increasing its access, in which case we
7160 // should redeclare it.
7161 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007162 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007163 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7164 I != E; ++I) {
7165 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007166 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7167 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7168 PrevShadow = Shadow;
7169 FoundEquivalentDecl = true;
7170 }
John McCalla17e83e2009-12-11 02:33:26 +00007171
7172 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7173 }
7174
Richard Smithfd8634a2013-10-23 02:17:46 +00007175 if (FoundEquivalentDecl)
7176 return false;
7177
Alp Tokera2794f92014-01-22 07:29:52 +00007178 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007179 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007180 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007181 case Ovl_Overload:
7182 return false;
7183
7184 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007185 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007186 break;
Richard Smith18819302014-02-06 01:31:33 +00007187
John McCall84d87672009-12-10 09:41:52 +00007188 // We found a decl with the exact signature.
7189 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007190 // If we're in a record, we want to hide the target, so we
7191 // return true (without a diagnostic) to tell the caller not to
7192 // build a shadow decl.
7193 if (CurContext->isRecord())
7194 return true;
7195
7196 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007197 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007198 break;
7199 }
7200
7201 Diag(Target->getLocation(), diag::note_using_decl_target);
7202 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7203 return true;
7204 }
7205
7206 // Target is not a function.
7207
John McCall84d87672009-12-10 09:41:52 +00007208 if (isa<TagDecl>(Target)) {
7209 // No conflict between a tag and a non-tag.
7210 if (!Tag) return false;
7211
John McCalle29c5cd2009-12-10 19:51:03 +00007212 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007213 Diag(Target->getLocation(), diag::note_using_decl_target);
7214 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7215 return true;
7216 }
7217
7218 // No conflict between a tag and a non-tag.
7219 if (!NonTag) return false;
7220
John McCalle29c5cd2009-12-10 19:51:03 +00007221 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007222 Diag(Target->getLocation(), diag::note_using_decl_target);
7223 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7224 return true;
7225}
7226
John McCall3f746822009-11-17 05:59:44 +00007227/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007228UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007229 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007230 NamedDecl *Orig,
7231 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007232
7233 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007234 NamedDecl *Target = Orig;
7235 if (isa<UsingShadowDecl>(Target)) {
7236 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7237 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007238 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007239
John McCall3f746822009-11-17 05:59:44 +00007240 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007241 = UsingShadowDecl::Create(Context, CurContext,
7242 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007243 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007244
Douglas Gregor457104e2010-09-29 04:25:11 +00007245 Shadow->setAccess(UD->getAccess());
7246 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7247 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007248
7249 Shadow->setPreviousDecl(PrevDecl);
7250
John McCall3f746822009-11-17 05:59:44 +00007251 if (S)
John McCall3969e302009-12-08 07:46:18 +00007252 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007253 else
John McCall3969e302009-12-08 07:46:18 +00007254 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007255
John McCall3969e302009-12-08 07:46:18 +00007256
John McCall84d87672009-12-10 09:41:52 +00007257 return Shadow;
7258}
John McCall3969e302009-12-08 07:46:18 +00007259
John McCall84d87672009-12-10 09:41:52 +00007260/// Hides a using shadow declaration. This is required by the current
7261/// using-decl implementation when a resolvable using declaration in a
7262/// class is followed by a declaration which would hide or override
7263/// one or more of the using decl's targets; for example:
7264///
7265/// struct Base { void foo(int); };
7266/// struct Derived : Base {
7267/// using Base::foo;
7268/// void foo(int);
7269/// };
7270///
7271/// The governing language is C++03 [namespace.udecl]p12:
7272///
7273/// When a using-declaration brings names from a base class into a
7274/// derived class scope, member functions in the derived class
7275/// override and/or hide member functions with the same name and
7276/// parameter types in a base class (rather than conflicting).
7277///
7278/// There are two ways to implement this:
7279/// (1) optimistically create shadow decls when they're not hidden
7280/// by existing declarations, or
7281/// (2) don't create any shadow decls (or at least don't make them
7282/// visible) until we've fully parsed/instantiated the class.
7283/// The problem with (1) is that we might have to retroactively remove
7284/// a shadow decl, which requires several O(n) operations because the
7285/// decl structures are (very reasonably) not designed for removal.
7286/// (2) avoids this but is very fiddly and phase-dependent.
7287void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007288 if (Shadow->getDeclName().getNameKind() ==
7289 DeclarationName::CXXConversionFunctionName)
7290 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7291
John McCall84d87672009-12-10 09:41:52 +00007292 // Remove it from the DeclContext...
7293 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007294
John McCall84d87672009-12-10 09:41:52 +00007295 // ...and the scope, if applicable...
7296 if (S) {
John McCall48871652010-08-21 09:40:31 +00007297 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007298 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007299 }
7300
John McCall84d87672009-12-10 09:41:52 +00007301 // ...and the using decl.
7302 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7303
7304 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007305 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007306}
7307
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007308namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007309class UsingValidatorCCC : public CorrectionCandidateCallback {
7310public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007311 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7312 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007313 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007314 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007315
Craig Toppera798a9d2014-03-02 09:32:10 +00007316 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007317 NamedDecl *ND = Candidate.getCorrectionDecl();
7318
7319 // Keywords are not valid here.
7320 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007321 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007322
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007323 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7324 !isa<TypeDecl>(ND))
7325 return false;
7326
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007327 // Completely unqualified names are invalid for a 'using' declaration.
7328 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7329 return false;
7330
7331 if (isa<TypeDecl>(ND))
7332 return HasTypenameKeyword || !IsInstantiation;
7333
7334 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007335 }
7336
7337private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007338 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007339 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007340 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007341};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007342} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007343
John McCalle61f2ba2009-11-18 02:36:19 +00007344/// Builds a using declaration.
7345///
7346/// \param IsInstantiation - Whether this call arises from an
7347/// instantiation of an unresolved using declaration. We treat
7348/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007349NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7350 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007351 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007352 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007353 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007354 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007355 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007356 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007357 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007358 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007359 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007360
Anders Carlssonf038fc22009-08-28 05:49:21 +00007361 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007362
Anders Carlsson59140b32009-08-28 03:16:11 +00007363 if (SS.isEmpty()) {
7364 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007365 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007366 }
Mike Stump11289f42009-09-09 15:08:12 +00007367
John McCall84d87672009-12-10 09:41:52 +00007368 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007369 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007370 ForRedeclaration);
7371 Previous.setHideTags(false);
7372 if (S) {
7373 LookupName(Previous, S);
7374
7375 // It is really dumb that we have to do this.
7376 LookupResult::Filter F = Previous.makeFilter();
7377 while (F.hasNext()) {
7378 NamedDecl *D = F.next();
7379 if (!isDeclInScope(D, CurContext, S))
7380 F.erase();
7381 }
7382 F.done();
7383 } else {
7384 assert(IsInstantiation && "no scope in non-instantiation");
7385 assert(CurContext->isRecord() && "scope not record in instantiation");
7386 LookupQualifiedName(Previous, CurContext);
7387 }
7388
John McCall84d87672009-12-10 09:41:52 +00007389 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007390 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7391 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007392 return 0;
7393
7394 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007395 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7396 return 0;
7397
John McCall84c16cf2009-11-12 03:15:40 +00007398 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007399 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007400 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007401 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007402 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007403 // FIXME: not all declaration name kinds are legal here
7404 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7405 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007406 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007407 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007408 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007409 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7410 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007411 }
John McCallb96ec562009-12-04 22:46:56 +00007412 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007413 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007414 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007415 }
John McCallb96ec562009-12-04 22:46:56 +00007416 D->setAccess(AS);
7417 CurContext->addDecl(D);
7418
7419 if (!LookupContext) return D;
7420 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007421
John McCall0b66eb32010-05-01 00:40:08 +00007422 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007423 UD->setInvalidDecl();
7424 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007425 }
7426
Richard Smith23d55872012-04-02 01:30:27 +00007427 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007428 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007429 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007430 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007431 return UD;
7432 }
7433
7434 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007435
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007436 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007437
John McCall3969e302009-12-08 07:46:18 +00007438 // Unlike most lookups, we don't always want to hide tag
7439 // declarations: tag names are visible through the using declaration
7440 // even if hidden by ordinary names, *except* in a dependent context
7441 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007442 if (!IsInstantiation)
7443 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007444
John McCall5dadb652012-04-07 03:04:20 +00007445 // For the purposes of this lookup, we have a base object type
7446 // equal to that of the current context.
7447 if (CurContext->isRecord()) {
7448 R.setBaseObjectType(
7449 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7450 }
7451
John McCall27b18f82009-11-17 02:14:36 +00007452 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007453
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007454 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007455 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007456 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7457 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007458 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7459 R.getLookupKind(), S, &SS, CCC)){
7460 // We reject any correction for which ND would be NULL.
7461 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007462 R.setLookupName(Corrected.getCorrection());
7463 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007464 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007465 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007466 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7467 << NameInfo.getName() << LookupContext << 0
7468 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007469 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007470 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007471 << NameInfo.getName() << LookupContext << SS.getRange();
7472 UD->setInvalidDecl();
7473 return UD;
7474 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007475 }
7476
John McCallb96ec562009-12-04 22:46:56 +00007477 if (R.isAmbiguous()) {
7478 UD->setInvalidDecl();
7479 return UD;
7480 }
Mike Stump11289f42009-09-09 15:08:12 +00007481
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007482 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007483 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007484 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007485 Diag(IdentLoc, diag::err_using_typename_non_type);
7486 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7487 Diag((*I)->getUnderlyingDecl()->getLocation(),
7488 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007489 UD->setInvalidDecl();
7490 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007491 }
7492 } else {
7493 // If we asked for a non-typename and we got a type, error out,
7494 // but only if this is an instantiation of an unresolved using
7495 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007496 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007497 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7498 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007499 UD->setInvalidDecl();
7500 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007501 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007502 }
7503
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007504 // C++0x N2914 [namespace.udecl]p6:
7505 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007506 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007507 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7508 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007509 UD->setInvalidDecl();
7510 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007511 }
Mike Stump11289f42009-09-09 15:08:12 +00007512
John McCall84d87672009-12-10 09:41:52 +00007513 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007514 UsingShadowDecl *PrevDecl = 0;
7515 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7516 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007517 }
John McCall3f746822009-11-17 05:59:44 +00007518
7519 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007520}
7521
Sebastian Redl08905022011-02-05 19:23:19 +00007522/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007523bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007524 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007525
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007526 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007527 assert(SourceType &&
7528 "Using decl naming constructor doesn't have type in scope spec.");
7529 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7530
7531 // Check whether the named type is a direct base class.
7532 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7533 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7534 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7535 BaseIt != BaseE; ++BaseIt) {
7536 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7537 if (CanonicalSourceType == BaseType)
7538 break;
Richard Smith23d55872012-04-02 01:30:27 +00007539 if (BaseIt->getType()->isDependentType())
7540 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007541 }
7542
7543 if (BaseIt == BaseE) {
7544 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007545 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007546 diag::err_using_decl_constructor_not_in_direct_base)
7547 << UD->getNameInfo().getSourceRange()
7548 << QualType(SourceType, 0) << TargetClass;
7549 return true;
7550 }
7551
Richard Smith23d55872012-04-02 01:30:27 +00007552 if (!CurContext->isDependentContext())
7553 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007554
7555 return false;
7556}
7557
John McCall84d87672009-12-10 09:41:52 +00007558/// Checks that the given using declaration is not an invalid
7559/// redeclaration. Note that this is checking only for the using decl
7560/// itself, not for any ill-formedness among the UsingShadowDecls.
7561bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007562 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007563 const CXXScopeSpec &SS,
7564 SourceLocation NameLoc,
7565 const LookupResult &Prev) {
7566 // C++03 [namespace.udecl]p8:
7567 // C++0x [namespace.udecl]p10:
7568 // A using-declaration is a declaration and can therefore be used
7569 // repeatedly where (and only where) multiple declarations are
7570 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007571 //
John McCall032092f2010-11-29 18:01:58 +00007572 // That's in non-member contexts.
7573 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007574 return false;
7575
Aaron Ballman4a979672014-01-03 13:56:08 +00007576 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007577
7578 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7579 NamedDecl *D = *I;
7580
7581 bool DTypename;
7582 NestedNameSpecifier *DQual;
7583 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007584 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007585 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007586 } else if (UnresolvedUsingValueDecl *UD
7587 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7588 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007589 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007590 } else if (UnresolvedUsingTypenameDecl *UD
7591 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7592 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007593 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007594 } else continue;
7595
7596 // using decls differ if one says 'typename' and the other doesn't.
7597 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007598 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007599
7600 // using decls differ if they name different scopes (but note that
7601 // template instantiation can cause this check to trigger when it
7602 // didn't before instantiation).
7603 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7604 Context.getCanonicalNestedNameSpecifier(DQual))
7605 continue;
7606
7607 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007608 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007609 return true;
7610 }
7611
7612 return false;
7613}
7614
John McCall3969e302009-12-08 07:46:18 +00007615
John McCallb96ec562009-12-04 22:46:56 +00007616/// Checks that the given nested-name qualifier used in a using decl
7617/// in the current context is appropriately related to the current
7618/// scope. If an error is found, diagnoses it and returns true.
7619bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7620 const CXXScopeSpec &SS,
7621 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007622 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007623
John McCall3969e302009-12-08 07:46:18 +00007624 if (!CurContext->isRecord()) {
7625 // C++03 [namespace.udecl]p3:
7626 // C++0x [namespace.udecl]p8:
7627 // A using-declaration for a class member shall be a member-declaration.
7628
7629 // If we weren't able to compute a valid scope, it must be a
7630 // dependent class scope.
7631 if (!NamedContext || NamedContext->isRecord()) {
7632 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7633 << SS.getRange();
7634 return true;
7635 }
7636
7637 // Otherwise, everything is known to be fine.
7638 return false;
7639 }
7640
7641 // The current scope is a record.
7642
7643 // If the named context is dependent, we can't decide much.
7644 if (!NamedContext) {
7645 // FIXME: in C++0x, we can diagnose if we can prove that the
7646 // nested-name-specifier does not refer to a base class, which is
7647 // still possible in some cases.
7648
7649 // Otherwise we have to conservatively report that things might be
7650 // okay.
7651 return false;
7652 }
7653
7654 if (!NamedContext->isRecord()) {
7655 // Ideally this would point at the last name in the specifier,
7656 // but we don't have that level of source info.
7657 Diag(SS.getRange().getBegin(),
7658 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007659 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007660 return true;
7661 }
7662
Douglas Gregor7c842292010-12-21 07:41:49 +00007663 if (!NamedContext->isDependentContext() &&
7664 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7665 return true;
7666
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007667 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007668 // C++0x [namespace.udecl]p3:
7669 // In a using-declaration used as a member-declaration, the
7670 // nested-name-specifier shall name a base class of the class
7671 // being defined.
7672
7673 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7674 cast<CXXRecordDecl>(NamedContext))) {
7675 if (CurContext == NamedContext) {
7676 Diag(NameLoc,
7677 diag::err_using_decl_nested_name_specifier_is_current_class)
7678 << SS.getRange();
7679 return true;
7680 }
7681
7682 Diag(SS.getRange().getBegin(),
7683 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007684 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007685 << cast<CXXRecordDecl>(CurContext)
7686 << SS.getRange();
7687 return true;
7688 }
7689
7690 return false;
7691 }
7692
7693 // C++03 [namespace.udecl]p4:
7694 // A using-declaration used as a member-declaration shall refer
7695 // to a member of a base class of the class being defined [etc.].
7696
7697 // Salient point: SS doesn't have to name a base class as long as
7698 // lookup only finds members from base classes. Therefore we can
7699 // diagnose here only if we can prove that that can't happen,
7700 // i.e. if the class hierarchies provably don't intersect.
7701
7702 // TODO: it would be nice if "definitely valid" results were cached
7703 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7704 // need to be repeated.
7705
7706 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007707 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007708
7709 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7710 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7711 Data->Bases.insert(Base);
7712 return true;
7713 }
7714
7715 bool hasDependentBases(const CXXRecordDecl *Class) {
7716 return !Class->forallBases(collect, this);
7717 }
7718
7719 /// Returns true if the base is dependent or is one of the
7720 /// accumulated base classes.
7721 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7722 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7723 return !Data->Bases.count(Base);
7724 }
7725
7726 bool mightShareBases(const CXXRecordDecl *Class) {
7727 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7728 }
7729 };
7730
7731 UserData Data;
7732
7733 // Returns false if we find a dependent base.
7734 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7735 return false;
7736
7737 // Returns false if the class has a dependent base or if it or one
7738 // of its bases is present in the base set of the current context.
7739 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7740 return false;
7741
7742 Diag(SS.getRange().getBegin(),
7743 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007744 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007745 << cast<CXXRecordDecl>(CurContext)
7746 << SS.getRange();
7747
7748 return true;
John McCallb96ec562009-12-04 22:46:56 +00007749}
7750
Richard Smithdda56e42011-04-15 14:24:37 +00007751Decl *Sema::ActOnAliasDeclaration(Scope *S,
7752 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007753 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007754 SourceLocation UsingLoc,
7755 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007756 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007757 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007758 // Skip up to the relevant declaration scope.
7759 while (S->getFlags() & Scope::TemplateParamScope)
7760 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007761 assert((S->getFlags() & Scope::DeclScope) &&
7762 "got alias-declaration outside of declaration scope");
7763
7764 if (Type.isInvalid())
7765 return 0;
7766
7767 bool Invalid = false;
7768 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7769 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007770 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007771
7772 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7773 return 0;
7774
7775 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007776 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007777 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007778 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7779 TInfo->getTypeLoc().getBeginLoc());
7780 }
Richard Smithdda56e42011-04-15 14:24:37 +00007781
7782 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7783 LookupName(Previous, S);
7784
7785 // Warn about shadowing the name of a template parameter.
7786 if (Previous.isSingleResult() &&
7787 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007788 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007789 Previous.clear();
7790 }
7791
7792 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7793 "name in alias declaration must be an identifier");
7794 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7795 Name.StartLocation,
7796 Name.Identifier, TInfo);
7797
7798 NewTD->setAccess(AS);
7799
7800 if (Invalid)
7801 NewTD->setInvalidDecl();
7802
Richard Smith54ecd982013-02-20 19:22:51 +00007803 ProcessDeclAttributeList(S, NewTD, AttrList);
7804
Richard Smith3f1b5d02011-05-05 21:57:07 +00007805 CheckTypedefForVariablyModifiedType(S, NewTD);
7806 Invalid |= NewTD->isInvalidDecl();
7807
Richard Smithdda56e42011-04-15 14:24:37 +00007808 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007809
7810 NamedDecl *NewND;
7811 if (TemplateParamLists.size()) {
7812 TypeAliasTemplateDecl *OldDecl = 0;
7813 TemplateParameterList *OldTemplateParams = 0;
7814
7815 if (TemplateParamLists.size() != 1) {
7816 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007817 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7818 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007819 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007820 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007821
7822 // Only consider previous declarations in the same scope.
7823 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7824 /*ExplicitInstantiationOrSpecialization*/false);
7825 if (!Previous.empty()) {
7826 Redeclaration = true;
7827
7828 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7829 if (!OldDecl && !Invalid) {
7830 Diag(UsingLoc, diag::err_redefinition_different_kind)
7831 << Name.Identifier;
7832
7833 NamedDecl *OldD = Previous.getRepresentativeDecl();
7834 if (OldD->getLocation().isValid())
7835 Diag(OldD->getLocation(), diag::note_previous_definition);
7836
7837 Invalid = true;
7838 }
7839
7840 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7841 if (TemplateParameterListsAreEqual(TemplateParams,
7842 OldDecl->getTemplateParameters(),
7843 /*Complain=*/true,
7844 TPL_TemplateMatch))
7845 OldTemplateParams = OldDecl->getTemplateParameters();
7846 else
7847 Invalid = true;
7848
7849 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7850 if (!Invalid &&
7851 !Context.hasSameType(OldTD->getUnderlyingType(),
7852 NewTD->getUnderlyingType())) {
7853 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7854 // but we can't reasonably accept it.
7855 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7856 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7857 if (OldTD->getLocation().isValid())
7858 Diag(OldTD->getLocation(), diag::note_previous_definition);
7859 Invalid = true;
7860 }
7861 }
7862 }
7863
7864 // Merge any previous default template arguments into our parameters,
7865 // and check the parameter list.
7866 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7867 TPC_TypeAliasTemplate))
7868 return 0;
7869
7870 TypeAliasTemplateDecl *NewDecl =
7871 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7872 Name.Identifier, TemplateParams,
7873 NewTD);
7874
7875 NewDecl->setAccess(AS);
7876
7877 if (Invalid)
7878 NewDecl->setInvalidDecl();
7879 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007880 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007881
7882 NewND = NewDecl;
7883 } else {
7884 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7885 NewND = NewTD;
7886 }
Richard Smithdda56e42011-04-15 14:24:37 +00007887
7888 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007889 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007890
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007891 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007892 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007893}
7894
John McCall48871652010-08-21 09:40:31 +00007895Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007896 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007897 SourceLocation AliasLoc,
7898 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007899 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007900 SourceLocation IdentLoc,
7901 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007902
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007903 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007904 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7905 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007906
Anders Carlssondca83c42009-03-28 06:23:46 +00007907 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007908 NamedDecl *PrevDecl
7909 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7910 ForRedeclaration);
7911 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7912 PrevDecl = 0;
7913
7914 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007915 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007916 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007917 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007918 // FIXME: At some point, we'll want to create the (redundant)
7919 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007920 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007921 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007922 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007923 }
Mike Stump11289f42009-09-09 15:08:12 +00007924
Anders Carlssondca83c42009-03-28 06:23:46 +00007925 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7926 diag::err_redefinition_different_kind;
7927 Diag(AliasLoc, DiagID) << Alias;
7928 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007929 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007930 }
7931
John McCall27b18f82009-11-17 02:14:36 +00007932 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007933 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007934
John McCall9f3059a2009-10-09 21:13:30 +00007935 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007936 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007937 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007938 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007939 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007940 }
Mike Stump11289f42009-09-09 15:08:12 +00007941
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007942 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007943 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007944 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007945 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007946
John McCalld8d0d432010-02-16 06:53:13 +00007947 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007948 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007949}
7950
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007951Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007952Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7953 CXXMethodDecl *MD) {
7954 CXXRecordDecl *ClassDecl = MD->getParent();
7955
Douglas Gregor6d880b12010-07-01 22:31:05 +00007956 // C++ [except.spec]p14:
7957 // An implicitly declared special member function (Clause 12) shall have an
7958 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007959 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007960 if (ClassDecl->isInvalidDecl())
7961 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007962
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007963 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00007964 for (const auto &B : ClassDecl->bases()) {
7965 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007966 continue;
7967
Aaron Ballman574705e2014-03-13 15:41:46 +00007968 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007969 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007970 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7971 // If this is a deleted function, add it anyway. This might be conformant
7972 // with the standard. This might not. I'm not sure. It might not matter.
7973 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00007974 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007975 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007976 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007977
7978 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00007979 for (const auto &B : ClassDecl->vbases()) {
7980 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007981 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007982 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7983 // If this is a deleted function, add it anyway. This might be conformant
7984 // with the standard. This might not. I'm not sure. It might not matter.
7985 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00007986 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007987 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007988 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007989
7990 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007991 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00007992 if (F->hasInClassInitializer()) {
7993 if (Expr *E = F->getInClassInitializer())
7994 ExceptSpec.CalledExpr(E);
7995 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00007996 // DR1351:
7997 // If the brace-or-equal-initializer of a non-static data member
7998 // invokes a defaulted default constructor of its class or of an
7999 // enclosing class in a potentially evaluated subexpression, the
8000 // program is ill-formed.
8001 //
8002 // This resolution is unworkable: the exception specification of the
8003 // default constructor can be needed in an unevaluated context, in
8004 // particular, in the operand of a noexcept-expression, and we can be
8005 // unable to compute an exception specification for an enclosed class.
8006 //
8007 // We do not allow an in-class initializer to require the evaluation
8008 // of the exception specification for any in-class initializer whose
8009 // definition is not lexically complete.
8010 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008011 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008012 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008013 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8014 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8015 // If this is a deleted function, add it anyway. This might be conformant
8016 // with the standard. This might not. I'm not sure. It might not matter.
8017 // In particular, the problem is that this function never gets called. It
8018 // might just be ill-formed because this function attempts to refer to
8019 // a deleted function here.
8020 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008021 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008022 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008023 }
John McCalldb40c7f2010-12-14 08:05:40 +00008024
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008025 return ExceptSpec;
8026}
8027
Richard Smithc2bc61b2013-03-18 21:12:30 +00008028Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008029Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8030 CXXRecordDecl *ClassDecl = CD->getParent();
8031
8032 // C++ [except.spec]p14:
8033 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008034 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008035 if (ClassDecl->isInvalidDecl())
8036 return ExceptSpec;
8037
8038 // Inherited constructor.
8039 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8040 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8041 // FIXME: Copying or moving the parameters could add extra exceptions to the
8042 // set, as could the default arguments for the inherited constructor. This
8043 // will be addressed when we implement the resolution of core issue 1351.
8044 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8045
8046 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008047 for (const auto &B : ClassDecl->bases()) {
8048 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008049 continue;
8050
Aaron Ballman574705e2014-03-13 15:41:46 +00008051 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008052 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8053 if (BaseClassDecl == InheritedDecl)
8054 continue;
8055 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8056 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008057 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008058 }
8059 }
8060
8061 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008062 for (const auto &B : ClassDecl->vbases()) {
8063 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008064 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8065 if (BaseClassDecl == InheritedDecl)
8066 continue;
8067 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8068 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008069 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008070 }
8071 }
8072
8073 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008074 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008075 if (F->hasInClassInitializer()) {
8076 if (Expr *E = F->getInClassInitializer())
8077 ExceptSpec.CalledExpr(E);
8078 else if (!F->isInvalidDecl())
8079 Diag(CD->getLocation(),
8080 diag::err_in_class_initializer_references_def_ctor) << CD;
8081 } else if (const RecordType *RecordTy
8082 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8083 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8084 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8085 if (Constructor)
8086 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8087 }
8088 }
8089
Richard Smithc2bc61b2013-03-18 21:12:30 +00008090 return ExceptSpec;
8091}
8092
Richard Smith8bf22e52012-11-29 01:34:07 +00008093namespace {
8094/// RAII object to register a special member as being currently declared.
8095struct DeclaringSpecialMember {
8096 Sema &S;
8097 Sema::SpecialMemberDecl D;
8098 bool WasAlreadyBeingDeclared;
8099
8100 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8101 : S(S), D(RD, CSM) {
8102 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8103 if (WasAlreadyBeingDeclared)
8104 // This almost never happens, but if it does, ensure that our cache
8105 // doesn't contain a stale result.
8106 S.SpecialMemberCache.clear();
8107
8108 // FIXME: Register a note to be produced if we encounter an error while
8109 // declaring the special member.
8110 }
8111 ~DeclaringSpecialMember() {
8112 if (!WasAlreadyBeingDeclared)
8113 S.SpecialMembersBeingDeclared.erase(D);
8114 }
8115
8116 /// \brief Are we already trying to declare this special member?
8117 bool isAlreadyBeingDeclared() const {
8118 return WasAlreadyBeingDeclared;
8119 }
8120};
8121}
8122
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008123CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8124 CXXRecordDecl *ClassDecl) {
8125 // C++ [class.ctor]p5:
8126 // A default constructor for a class X is a constructor of class X
8127 // that can be called without an argument. If there is no
8128 // user-declared constructor for class X, a default constructor is
8129 // implicitly declared. An implicitly-declared default constructor
8130 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008131 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008132 "Should not build implicit default constructor!");
8133
Richard Smith8bf22e52012-11-29 01:34:07 +00008134 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8135 if (DSM.isAlreadyBeingDeclared())
8136 return 0;
8137
Richard Smithb5800092012-06-10 05:43:50 +00008138 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8139 CXXDefaultConstructor,
8140 false);
8141
Douglas Gregor6d880b12010-07-01 22:31:05 +00008142 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008143 CanQualType ClassType
8144 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008145 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008146 DeclarationName Name
8147 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008148 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008149 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008150 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008151 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008152 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008153 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008154 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008155 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008156
8157 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008158 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008159 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008160
Richard Smith6b02d462012-12-08 08:32:28 +00008161 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8162 // constructors is easy to compute.
8163 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8164
8165 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008166 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008167
Douglas Gregor9672f922010-07-03 00:47:00 +00008168 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008169 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008170
Douglas Gregor0be31a22010-07-02 17:43:08 +00008171 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008172 PushOnScopeChains(DefaultCon, S, false);
8173 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008174
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008175 return DefaultCon;
8176}
8177
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008178void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8179 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008180 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008181 !Constructor->doesThisDeclarationHaveABody() &&
8182 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008183 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008184
Anders Carlsson423f5d82010-04-23 16:04:08 +00008185 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008186 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008187
Eli Friedmaneaf34142012-10-18 20:14:08 +00008188 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008189 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008190 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008191 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008192 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008193 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008194 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008195 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008196 }
Douglas Gregor73193272010-09-20 16:48:21 +00008197
8198 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008199 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008200
Eli Friedman276dd182013-09-05 00:02:25 +00008201 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008202 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008203
8204 if (ASTMutationListener *L = getASTMutationListener()) {
8205 L->CompletedImplicitDefinition(Constructor);
8206 }
Richard Trieuef64e942013-10-25 00:56:00 +00008207
8208 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008209}
8210
Richard Smith938f40b2011-06-11 17:19:42 +00008211void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008212 // Perform any delayed checks on exception specifications.
8213 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008214}
8215
Richard Smith185be182013-04-10 05:48:59 +00008216namespace {
8217/// Information on inheriting constructors to declare.
8218class InheritingConstructorInfo {
8219public:
8220 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8221 : SemaRef(SemaRef), Derived(Derived) {
8222 // Mark the constructors that we already have in the derived class.
8223 //
8224 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8225 // unless there is a user-declared constructor with the same signature in
8226 // the class where the using-declaration appears.
8227 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8228 }
8229
8230 void inheritAll(CXXRecordDecl *RD) {
8231 visitAll(RD, &InheritingConstructorInfo::inherit);
8232 }
8233
8234private:
8235 /// Information about an inheriting constructor.
8236 struct InheritingConstructor {
8237 InheritingConstructor()
8238 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8239
8240 /// If \c true, a constructor with this signature is already declared
8241 /// in the derived class.
8242 bool DeclaredInDerived;
8243
8244 /// The constructor which is inherited.
8245 const CXXConstructorDecl *BaseCtor;
8246
8247 /// The derived constructor we declared.
8248 CXXConstructorDecl *DerivedCtor;
8249 };
8250
8251 /// Inheriting constructors with a given canonical type. There can be at
8252 /// most one such non-template constructor, and any number of templated
8253 /// constructors.
8254 struct InheritingConstructorsForType {
8255 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008256 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8257 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008258
8259 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8260 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8261 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8262 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8263 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8264 false, S.TPL_TemplateMatch))
8265 return Templates[I].second;
8266 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8267 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008268 }
Richard Smith185be182013-04-10 05:48:59 +00008269
8270 return NonTemplate;
8271 }
8272 };
8273
8274 /// Get or create the inheriting constructor record for a constructor.
8275 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8276 QualType CtorType) {
8277 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8278 .getEntry(SemaRef, Ctor);
8279 }
8280
8281 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8282
8283 /// Process all constructors for a class.
8284 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008285 for (const auto *Ctor : RD->ctors())
8286 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008287 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8288 I(RD->decls_begin()), E(RD->decls_end());
8289 I != E; ++I) {
8290 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8291 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8292 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008293 }
8294 }
Richard Smith185be182013-04-10 05:48:59 +00008295
8296 /// Note that a constructor (or constructor template) was declared in Derived.
8297 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8298 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8299 }
8300
8301 /// Inherit a single constructor.
8302 void inherit(const CXXConstructorDecl *Ctor) {
8303 const FunctionProtoType *CtorType =
8304 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008305 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008306 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8307
8308 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8309
8310 // Core issue (no number yet): the ellipsis is always discarded.
8311 if (EPI.Variadic) {
8312 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8313 SemaRef.Diag(Ctor->getLocation(),
8314 diag::note_using_decl_constructor_ellipsis);
8315 EPI.Variadic = false;
8316 }
8317
8318 // Declare a constructor for each number of parameters.
8319 //
8320 // C++11 [class.inhctor]p1:
8321 // The candidate set of inherited constructors from the class X named in
8322 // the using-declaration consists of [... modulo defects ...] for each
8323 // constructor or constructor template of X, the set of constructors or
8324 // constructor templates that results from omitting any ellipsis parameter
8325 // specification and successively omitting parameters with a default
8326 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008327 unsigned MinParams = minParamsToInherit(Ctor);
8328 unsigned Params = Ctor->getNumParams();
8329 if (Params >= MinParams) {
8330 do
8331 declareCtor(UsingLoc, Ctor,
8332 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008333 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008334 while (Params > MinParams &&
8335 Ctor->getParamDecl(--Params)->hasDefaultArg());
8336 }
Richard Smith185be182013-04-10 05:48:59 +00008337 }
8338
8339 /// Find the using-declaration which specified that we should inherit the
8340 /// constructors of \p Base.
8341 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8342 // No fancy lookup required; just look for the base constructor name
8343 // directly within the derived class.
8344 ASTContext &Context = SemaRef.Context;
8345 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8346 Context.getCanonicalType(Context.getRecordType(Base)));
8347 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8348 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8349 }
8350
8351 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8352 // C++11 [class.inhctor]p3:
8353 // [F]or each constructor template in the candidate set of inherited
8354 // constructors, a constructor template is implicitly declared
8355 if (Ctor->getDescribedFunctionTemplate())
8356 return 0;
8357
8358 // For each non-template constructor in the candidate set of inherited
8359 // constructors other than a constructor having no parameters or a
8360 // copy/move constructor having a single parameter, a constructor is
8361 // implicitly declared [...]
8362 if (Ctor->getNumParams() == 0)
8363 return 1;
8364 if (Ctor->isCopyOrMoveConstructor())
8365 return 2;
8366
8367 // Per discussion on core reflector, never inherit a constructor which
8368 // would become a default, copy, or move constructor of Derived either.
8369 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8370 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8371 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8372 }
8373
8374 /// Declare a single inheriting constructor, inheriting the specified
8375 /// constructor, with the given type.
8376 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8377 QualType DerivedType) {
8378 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8379
8380 // C++11 [class.inhctor]p3:
8381 // ... a constructor is implicitly declared with the same constructor
8382 // characteristics unless there is a user-declared constructor with
8383 // the same signature in the class where the using-declaration appears
8384 if (Entry.DeclaredInDerived)
8385 return;
8386
8387 // C++11 [class.inhctor]p7:
8388 // If two using-declarations declare inheriting constructors with the
8389 // same signature, the program is ill-formed
8390 if (Entry.DerivedCtor) {
8391 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8392 // Only diagnose this once per constructor.
8393 if (Entry.DerivedCtor->isInvalidDecl())
8394 return;
8395 Entry.DerivedCtor->setInvalidDecl();
8396
8397 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8398 SemaRef.Diag(BaseCtor->getLocation(),
8399 diag::note_using_decl_constructor_conflict_current_ctor);
8400 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8401 diag::note_using_decl_constructor_conflict_previous_ctor);
8402 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8403 diag::note_using_decl_constructor_conflict_previous_using);
8404 } else {
8405 // Core issue (no number): if the same inheriting constructor is
8406 // produced by multiple base class constructors from the same base
8407 // class, the inheriting constructor is defined as deleted.
8408 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8409 }
8410
8411 return;
8412 }
8413
8414 ASTContext &Context = SemaRef.Context;
8415 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8416 Context.getCanonicalType(Context.getRecordType(Derived)));
8417 DeclarationNameInfo NameInfo(Name, UsingLoc);
8418
8419 TemplateParameterList *TemplateParams = 0;
8420 if (const FunctionTemplateDecl *FTD =
8421 BaseCtor->getDescribedFunctionTemplate()) {
8422 TemplateParams = FTD->getTemplateParameters();
8423 // We're reusing template parameters from a different DeclContext. This
8424 // is questionable at best, but works out because the template depth in
8425 // both places is guaranteed to be 0.
8426 // FIXME: Rebuild the template parameters in the new context, and
8427 // transform the function type to refer to them.
8428 }
8429
8430 // Build type source info pointing at the using-declaration. This is
8431 // required by template instantiation.
8432 TypeSourceInfo *TInfo =
8433 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8434 FunctionProtoTypeLoc ProtoLoc =
8435 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8436
8437 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8438 Context, Derived, UsingLoc, NameInfo, DerivedType,
8439 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8440 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8441
8442 // Build an unevaluated exception specification for this constructor.
8443 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8444 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8445 EPI.ExceptionSpecType = EST_Unevaluated;
8446 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008447 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008448 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008449
8450 // Build the parameter declarations.
8451 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008452 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008453 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008454 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008455 ParmVarDecl *PD = ParmVarDecl::Create(
8456 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008457 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008458 PD->setScopeInfo(0, I);
8459 PD->setImplicit();
8460 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008461 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008462 }
8463
8464 // Set up the new constructor.
8465 DerivedCtor->setAccess(BaseCtor->getAccess());
8466 DerivedCtor->setParams(ParamDecls);
8467 DerivedCtor->setInheritedConstructor(BaseCtor);
8468 if (BaseCtor->isDeleted())
8469 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8470
8471 // If this is a constructor template, build the template declaration.
8472 if (TemplateParams) {
8473 FunctionTemplateDecl *DerivedTemplate =
8474 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8475 TemplateParams, DerivedCtor);
8476 DerivedTemplate->setAccess(BaseCtor->getAccess());
8477 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8478 Derived->addDecl(DerivedTemplate);
8479 } else {
8480 Derived->addDecl(DerivedCtor);
8481 }
8482
8483 Entry.BaseCtor = BaseCtor;
8484 Entry.DerivedCtor = DerivedCtor;
8485 }
8486
8487 Sema &SemaRef;
8488 CXXRecordDecl *Derived;
8489 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8490 MapType Map;
8491};
8492}
8493
8494void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8495 // Defer declaring the inheriting constructors until the class is
8496 // instantiated.
8497 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008498 return;
8499
Richard Smith185be182013-04-10 05:48:59 +00008500 // Find base classes from which we might inherit constructors.
8501 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008502 for (const auto &BaseIt : ClassDecl->bases())
8503 if (BaseIt.getInheritConstructors())
8504 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008505
Richard Smith185be182013-04-10 05:48:59 +00008506 // Go no further if we're not inheriting any constructors.
8507 if (InheritedBases.empty())
8508 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008509
Richard Smith185be182013-04-10 05:48:59 +00008510 // Declare the inherited constructors.
8511 InheritingConstructorInfo ICI(*this, ClassDecl);
8512 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8513 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008514}
8515
Richard Smithc2bc61b2013-03-18 21:12:30 +00008516void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8517 CXXConstructorDecl *Constructor) {
8518 CXXRecordDecl *ClassDecl = Constructor->getParent();
8519 assert(Constructor->getInheritedConstructor() &&
8520 !Constructor->doesThisDeclarationHaveABody() &&
8521 !Constructor->isDeleted());
8522
8523 SynthesizedFunctionScope Scope(*this, Constructor);
8524 DiagnosticErrorTrap Trap(Diags);
8525 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8526 Trap.hasErrorOccurred()) {
8527 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8528 << Context.getTagDeclType(ClassDecl);
8529 Constructor->setInvalidDecl();
8530 return;
8531 }
8532
8533 SourceLocation Loc = Constructor->getLocation();
8534 Constructor->setBody(new (Context) CompoundStmt(Loc));
8535
Eli Friedman276dd182013-09-05 00:02:25 +00008536 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008537 MarkVTableUsed(CurrentLocation, ClassDecl);
8538
8539 if (ASTMutationListener *L = getASTMutationListener()) {
8540 L->CompletedImplicitDefinition(Constructor);
8541 }
8542}
8543
8544
Alexis Huntf91729462011-05-12 22:46:25 +00008545Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008546Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8547 CXXRecordDecl *ClassDecl = MD->getParent();
8548
Douglas Gregorf1203042010-07-01 19:09:28 +00008549 // C++ [except.spec]p14:
8550 // An implicitly declared special member function (Clause 12) shall have
8551 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008552 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008553 if (ClassDecl->isInvalidDecl())
8554 return ExceptSpec;
8555
Douglas Gregorf1203042010-07-01 19:09:28 +00008556 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008557 for (const auto &B : ClassDecl->bases()) {
8558 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008559 continue;
8560
Aaron Ballman574705e2014-03-13 15:41:46 +00008561 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8562 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008563 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008564 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008565
Douglas Gregorf1203042010-07-01 19:09:28 +00008566 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008567 for (const auto &B : ClassDecl->vbases()) {
8568 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8569 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008570 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008571 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008572
Douglas Gregorf1203042010-07-01 19:09:28 +00008573 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008574 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008575 if (const RecordType *RecordTy
8576 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008577 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008578 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008579 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008580
Alexis Huntf91729462011-05-12 22:46:25 +00008581 return ExceptSpec;
8582}
8583
8584CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8585 // C++ [class.dtor]p2:
8586 // If a class has no user-declared destructor, a destructor is
8587 // declared implicitly. An implicitly-declared destructor is an
8588 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008589 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008590
Richard Smith8bf22e52012-11-29 01:34:07 +00008591 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8592 if (DSM.isAlreadyBeingDeclared())
8593 return 0;
8594
Douglas Gregor7454c562010-07-02 20:37:36 +00008595 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008596 CanQualType ClassType
8597 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008598 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008599 DeclarationName Name
8600 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008601 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008602 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008603 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8604 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008605 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008606 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008607 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008608 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008609
8610 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008611 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008612 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008613
Richard Smith6b02d462012-12-08 08:32:28 +00008614 AddOverriddenMethods(ClassDecl, Destructor);
8615
8616 // We don't need to use SpecialMemberIsTrivial here; triviality for
8617 // destructors is easy to compute.
8618 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8619
8620 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008621 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008622
Douglas Gregor7454c562010-07-02 20:37:36 +00008623 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008624 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008625
Douglas Gregor7454c562010-07-02 20:37:36 +00008626 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008627 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008628 PushOnScopeChains(Destructor, S, false);
8629 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008630
Douglas Gregorf1203042010-07-01 19:09:28 +00008631 return Destructor;
8632}
8633
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008634void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008635 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008636 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008637 !Destructor->doesThisDeclarationHaveABody() &&
8638 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008639 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008640 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008641 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008642
Douglas Gregor54818f02010-05-12 16:39:35 +00008643 if (Destructor->isInvalidDecl())
8644 return;
8645
Eli Friedmaneaf34142012-10-18 20:14:08 +00008646 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008647
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008648 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008649 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8650 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008651
Douglas Gregor54818f02010-05-12 16:39:35 +00008652 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008653 Diag(CurrentLocation, diag::note_member_synthesized_at)
8654 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8655
8656 Destructor->setInvalidDecl();
8657 return;
8658 }
8659
Douglas Gregor73193272010-09-20 16:48:21 +00008660 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008661 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008662 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008663 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008664
8665 if (ASTMutationListener *L = getASTMutationListener()) {
8666 L->CompletedImplicitDefinition(Destructor);
8667 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008668}
8669
Richard Smith84973e52012-04-21 18:42:51 +00008670/// \brief Perform any semantic analysis which needs to be delayed until all
8671/// pending class member declarations have been parsed.
8672void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008673 // If the context is an invalid C++ class, just suppress these checks.
8674 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8675 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008676 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008677 DelayedDestructorExceptionSpecChecks.clear();
8678 return;
8679 }
8680 }
Richard Smith84973e52012-04-21 18:42:51 +00008681}
8682
Richard Smithd3b5c9082012-07-27 04:22:15 +00008683void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8684 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008685 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008686 "adjusting dtor exception specs was introduced in c++11");
8687
Sebastian Redl623ea822011-05-19 05:13:44 +00008688 // C++11 [class.dtor]p3:
8689 // A declaration of a destructor that does not have an exception-
8690 // specification is implicitly considered to have the same exception-
8691 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008692 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008693 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008694 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008695 return;
8696
Chandler Carruth9a797572011-09-20 04:55:26 +00008697 // Replace the destructor's type, building off the existing one. Fortunately,
8698 // the only thing of interest in the destructor type is its extended info.
8699 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008700 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8701 EPI.ExceptionSpecType = EST_Unevaluated;
8702 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008703 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008704
Sebastian Redl623ea822011-05-19 05:13:44 +00008705 // FIXME: If the destructor has a body that could throw, and the newly created
8706 // spec doesn't allow exceptions, we should emit a warning, because this
8707 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008708 // However, we don't have a body or an exception specification yet, so it
8709 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008710}
8711
Pavel Labath58934982013-08-30 08:52:28 +00008712namespace {
8713/// \brief An abstract base class for all helper classes used in building the
8714// copy/move operators. These classes serve as factory functions and help us
8715// avoid using the same Expr* in the AST twice.
8716class ExprBuilder {
8717 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8718 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8719
8720protected:
8721 static Expr *assertNotNull(Expr *E) {
8722 assert(E && "Expression construction must not fail.");
8723 return E;
8724 }
8725
8726public:
8727 ExprBuilder() {}
8728 virtual ~ExprBuilder() {}
8729
8730 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8731};
8732
8733class RefBuilder: public ExprBuilder {
8734 VarDecl *Var;
8735 QualType VarType;
8736
8737public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008738 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008739 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8740 }
8741
8742 RefBuilder(VarDecl *Var, QualType VarType)
8743 : Var(Var), VarType(VarType) {}
8744};
8745
8746class ThisBuilder: public ExprBuilder {
8747public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008748 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008749 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8750 }
8751};
8752
8753class CastBuilder: public ExprBuilder {
8754 const ExprBuilder &Builder;
8755 QualType Type;
8756 ExprValueKind Kind;
8757 const CXXCastPath &Path;
8758
8759public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008760 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008761 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8762 CK_UncheckedDerivedToBase, Kind,
8763 &Path).take());
8764 }
8765
8766 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8767 const CXXCastPath &Path)
8768 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8769};
8770
8771class DerefBuilder: public ExprBuilder {
8772 const ExprBuilder &Builder;
8773
8774public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008775 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008776 return assertNotNull(
8777 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8778 }
8779
8780 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8781};
8782
8783class MemberBuilder: public ExprBuilder {
8784 const ExprBuilder &Builder;
8785 QualType Type;
8786 CXXScopeSpec SS;
8787 bool IsArrow;
8788 LookupResult &MemberLookup;
8789
8790public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008791 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008792 return assertNotNull(S.BuildMemberReferenceExpr(
8793 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8794 MemberLookup, 0).take());
8795 }
8796
8797 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8798 LookupResult &MemberLookup)
8799 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8800 MemberLookup(MemberLookup) {}
8801};
8802
8803class MoveCastBuilder: public ExprBuilder {
8804 const ExprBuilder &Builder;
8805
8806public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008807 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008808 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8809 }
8810
8811 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8812};
8813
8814class LvalueConvBuilder: public ExprBuilder {
8815 const ExprBuilder &Builder;
8816
8817public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008818 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008819 return assertNotNull(
8820 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8821 }
8822
8823 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8824};
8825
8826class SubscriptBuilder: public ExprBuilder {
8827 const ExprBuilder &Base;
8828 const ExprBuilder &Index;
8829
8830public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008831 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008832 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8833 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8834 }
8835
8836 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8837 : Base(Base), Index(Index) {}
8838};
8839
8840} // end anonymous namespace
8841
Richard Smith41ae3282012-11-14 00:50:40 +00008842/// When generating a defaulted copy or move assignment operator, if a field
8843/// should be copied with __builtin_memcpy rather than via explicit assignments,
8844/// do so. This optimization only applies for arrays of scalars, and for arrays
8845/// of class type where the selected copy/move-assignment operator is trivial.
8846static StmtResult
8847buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008848 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008849 // Compute the size of the memory buffer to be copied.
8850 QualType SizeType = S.Context.getSizeType();
8851 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8852 S.Context.getTypeSizeInChars(T).getQuantity());
8853
8854 // Take the address of the field references for "from" and "to". We
8855 // directly construct UnaryOperators here because semantic analysis
8856 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008857 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008858 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8859 S.Context.getPointerType(From->getType()),
8860 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008861 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008862 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8863 S.Context.getPointerType(To->getType()),
8864 VK_RValue, OK_Ordinary, Loc);
8865
8866 const Type *E = T->getBaseElementTypeUnsafe();
8867 bool NeedsCollectableMemCpy =
8868 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8869
8870 // Create a reference to the __builtin_objc_memmove_collectable function
8871 StringRef MemCpyName = NeedsCollectableMemCpy ?
8872 "__builtin_objc_memmove_collectable" :
8873 "__builtin_memcpy";
8874 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8875 Sema::LookupOrdinaryName);
8876 S.LookupName(R, S.TUScope, true);
8877
8878 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8879 if (!MemCpy)
8880 // Something went horribly wrong earlier, and we will have complained
8881 // about it.
8882 return StmtError();
8883
8884 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8885 VK_RValue, Loc, 0);
8886 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8887
8888 Expr *CallArgs[] = {
8889 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8890 };
8891 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8892 Loc, CallArgs, Loc);
8893
8894 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8895 return S.Owned(Call.takeAs<Stmt>());
8896}
8897
Sebastian Redl22653ba2011-08-30 19:58:05 +00008898/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008899/// \c To.
8900///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008901/// This routine is used to copy/move the members of a class with an
8902/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008903/// copied are arrays, this routine builds for loops to copy them.
8904///
8905/// \param S The Sema object used for type-checking.
8906///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008907/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008908///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008909/// \param T The type of the expressions being copied/moved. Both expressions
8910/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008911///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008912/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008913///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008914/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008915///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008916/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008917/// Otherwise, it's a non-static member subobject.
8918///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008919/// \param Copying Whether we're copying or moving.
8920///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008921/// \param Depth Internal parameter recording the depth of the recursion.
8922///
Richard Smith41ae3282012-11-14 00:50:40 +00008923/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8924/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008925static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008926buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008927 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008928 bool CopyingBaseSubobject, bool Copying,
8929 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008930 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008931 // Each subobject is assigned in the manner appropriate to its type:
8932 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008933 // - if the subobject is of class type, as if by a call to operator= with
8934 // the subobject as the object expression and the corresponding
8935 // subobject of x as a single function argument (as if by explicit
8936 // qualification; that is, ignoring any possible virtual overriding
8937 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008938 //
8939 // C++03 [class.copy]p13:
8940 // - if the subobject is of class type, the copy assignment operator for
8941 // the class is used (as if by explicit qualification; that is,
8942 // ignoring any possible virtual overriding functions in more derived
8943 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008944 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8945 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008946
Douglas Gregorb139cd52010-05-01 20:49:11 +00008947 // Look for operator=.
8948 DeclarationName Name
8949 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8950 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8951 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008952
Richard Smith52c0b582012-11-13 00:54:12 +00008953 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8954 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008955 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008956 LookupResult::Filter F = OpLookup.makeFilter();
8957 while (F.hasNext()) {
8958 NamedDecl *D = F.next();
8959 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8960 if (Method->isCopyAssignmentOperator() ||
8961 (!Copying && Method->isMoveAssignmentOperator()))
8962 continue;
8963
8964 F.erase();
8965 }
8966 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008967 }
Richard Smith52c0b582012-11-13 00:54:12 +00008968
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008969 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008970 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008971 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008972 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008973 // ambiguities), we need to cast "this" to that subobject type; to
8974 // ensure that we don't go through the virtual call mechanism, we need
8975 // to qualify the operator= name with the base class (see below). However,
8976 // this means that if the base class has a protected copy assignment
8977 // operator, the protected member access check will fail. So, we
8978 // rewrite "protected" access to "public" access in this case, since we
8979 // know by construction that we're calling from a derived class.
8980 if (CopyingBaseSubobject) {
8981 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8982 L != LEnd; ++L) {
8983 if (L.getAccess() == AS_protected)
8984 L.setAccess(AS_public);
8985 }
8986 }
Richard Smith52c0b582012-11-13 00:54:12 +00008987
Douglas Gregorb139cd52010-05-01 20:49:11 +00008988 // Create the nested-name-specifier that will be used to qualify the
8989 // reference to operator=; this is required to suppress the virtual
8990 // call mechanism.
8991 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00008992 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00008993 SS.MakeTrivial(S.Context,
8994 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00008995 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00008996 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00008997
Douglas Gregorb139cd52010-05-01 20:49:11 +00008998 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00008999 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009000 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9001 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009002 /*FirstQualifierInScope=*/0,
9003 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009004 /*TemplateArgs=*/0,
9005 /*SuppressQualifierCheck=*/true);
9006 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009007 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009008
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009010
Pavel Labath58934982013-08-30 08:52:28 +00009011 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009012 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009013 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009014 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009015 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009016 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009017
Richard Smith41ae3282012-11-14 00:50:40 +00009018 // If we built a call to a trivial 'operator=' while copying an array,
9019 // bail out. We'll replace the whole shebang with a memcpy.
9020 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9021 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9022 return StmtResult((Stmt*)0);
9023
Richard Smith52c0b582012-11-13 00:54:12 +00009024 // Convert to an expression-statement, and clean up any produced
9025 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009026 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009027 }
John McCallab8c2732010-03-16 06:11:48 +00009028
Richard Smith52c0b582012-11-13 00:54:12 +00009029 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009030 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009031 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009032 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009033 ExprResult Assignment = S.CreateBuiltinBinOp(
9034 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009035 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009036 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009037 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009038 }
Richard Smith52c0b582012-11-13 00:54:12 +00009039
9040 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009041 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009042
Douglas Gregorb139cd52010-05-01 20:49:11 +00009043 // Construct a loop over the array bounds, e.g.,
9044 //
9045 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9046 //
9047 // that will copy each of the array elements.
9048 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009049
Douglas Gregorb139cd52010-05-01 20:49:11 +00009050 // Create the iteration variable.
9051 IdentifierInfo *IterationVarName = 0;
9052 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009053 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009054 llvm::raw_svector_ostream OS(Str);
9055 OS << "__i" << Depth;
9056 IterationVarName = &S.Context.Idents.get(OS.str());
9057 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009058 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009059 IterationVarName, SizeType,
9060 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009061 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009062
Douglas Gregorb139cd52010-05-01 20:49:11 +00009063 // Initialize the iteration variable to zero.
9064 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009065 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009066
Pavel Labath58934982013-08-30 08:52:28 +00009067 // Creates a reference to the iteration variable.
9068 RefBuilder IterationVarRef(IterationVar, SizeType);
9069 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009070
Douglas Gregorb139cd52010-05-01 20:49:11 +00009071 // Create the DeclStmt that holds the iteration variable.
9072 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009073
Douglas Gregorb139cd52010-05-01 20:49:11 +00009074 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009075 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9076 MoveCastBuilder FromIndexMove(FromIndexCopy);
9077 const ExprBuilder *FromIndex;
9078 if (Copying)
9079 FromIndex = &FromIndexCopy;
9080 else
9081 FromIndex = &FromIndexMove;
9082
9083 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009084
9085 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009086 StmtResult Copy =
9087 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009088 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009089 Copying, Depth + 1);
9090 // Bail out if copying fails or if we determined that we should use memcpy.
9091 if (Copy.isInvalid() || !Copy.get())
9092 return Copy;
9093
9094 // Create the comparison against the array bound.
9095 llvm::APInt Upper
9096 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9097 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009098 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009099 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9100 BO_NE, S.Context.BoolTy,
9101 VK_RValue, OK_Ordinary, Loc, false);
9102
9103 // Create the pre-increment of the iteration variable.
9104 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009105 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9106 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009107
Douglas Gregorb139cd52010-05-01 20:49:11 +00009108 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009109 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009110 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009111 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009112 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009113}
9114
Richard Smith41ae3282012-11-14 00:50:40 +00009115static StmtResult
9116buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009117 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009118 bool CopyingBaseSubobject, bool Copying) {
9119 // Maybe we should use a memcpy?
9120 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9121 T.isTriviallyCopyableType(S.Context))
9122 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9123
9124 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9125 CopyingBaseSubobject,
9126 Copying, 0));
9127
9128 // If we ended up picking a trivial assignment operator for an array of a
9129 // non-trivially-copyable class type, just emit a memcpy.
9130 if (!Result.isInvalid() && !Result.get())
9131 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9132
9133 return Result;
9134}
9135
Richard Smithd3b5c9082012-07-27 04:22:15 +00009136Sema::ImplicitExceptionSpecification
9137Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9138 CXXRecordDecl *ClassDecl = MD->getParent();
9139
9140 ImplicitExceptionSpecification ExceptSpec(*this);
9141 if (ClassDecl->isInvalidDecl())
9142 return ExceptSpec;
9143
9144 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009145 assert(T->getNumParams() == 1 && "not a copy assignment op");
9146 unsigned ArgQuals =
9147 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009148
Douglas Gregor68e11362010-07-01 17:48:08 +00009149 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009150 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009151 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009152
9153 // It is unspecified whether or not an implicit copy assignment operator
9154 // attempts to deduplicate calls to assignment operators of virtual bases are
9155 // made. As such, this exception specification is effectively unspecified.
9156 // Based on a similar decision made for constness in C++0x, we're erring on
9157 // the side of assuming such calls to be made regardless of whether they
9158 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009159 for (const auto &Base : ClassDecl->bases()) {
9160 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009161 continue;
9162
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009163 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009164 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009165 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9166 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009167 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009168 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009169
Aaron Ballman445a9392014-03-13 16:15:17 +00009170 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009171 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009172 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009173 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9174 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009175 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009176 }
9177
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009178 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009179 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009180 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9181 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009182 LookupCopyingAssignment(FieldClassDecl,
9183 ArgQuals | FieldType.getCVRQualifiers(),
9184 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009185 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009186 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009187 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009188
Richard Smithd3b5c9082012-07-27 04:22:15 +00009189 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009190}
9191
9192CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9193 // Note: The following rules are largely analoguous to the copy
9194 // constructor rules. Note that virtual bases are not taken into account
9195 // for determining the argument type of the operator. Note also that
9196 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009197 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009198
Richard Smith8bf22e52012-11-29 01:34:07 +00009199 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9200 if (DSM.isAlreadyBeingDeclared())
9201 return 0;
9202
Alexis Hunt119f3652011-05-14 05:23:20 +00009203 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9204 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009205 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9206 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009207 ArgType = ArgType.withConst();
9208 ArgType = Context.getLValueReferenceType(ArgType);
9209
Richard Smith99005e62013-05-07 03:19:20 +00009210 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9211 CXXCopyAssignment,
9212 Const);
9213
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009214 // An implicitly-declared copy assignment operator is an inline public
9215 // member of its class.
9216 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009217 SourceLocation ClassLoc = ClassDecl->getLocation();
9218 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009219 CXXMethodDecl *CopyAssignment =
9220 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9221 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9222 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009223 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009224 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009225 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009226
9227 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009228 FunctionProtoType::ExtProtoInfo EPI =
9229 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009230 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009231
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009232 // Add the parameter to the operator.
9233 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009234 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009235 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009236 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009237 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009238
Richard Smith6b02d462012-12-08 08:32:28 +00009239 AddOverriddenMethods(ClassDecl, CopyAssignment);
9240
9241 CopyAssignment->setTrivial(
9242 ClassDecl->needsOverloadResolutionForCopyAssignment()
9243 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9244 : ClassDecl->hasTrivialCopyAssignment());
9245
Richard Smith852265f2012-03-30 20:53:28 +00009246 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009247 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009248
Richard Smith6b02d462012-12-08 08:32:28 +00009249 // Note that we have added this copy-assignment operator.
9250 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9251
9252 if (Scope *S = getScopeForContext(ClassDecl))
9253 PushOnScopeChains(CopyAssignment, S, false);
9254 ClassDecl->addDecl(CopyAssignment);
9255
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009256 return CopyAssignment;
9257}
9258
Richard Smithd577fbb2013-06-13 03:23:42 +00009259/// Diagnose an implicit copy operation for a class which is odr-used, but
9260/// which is deprecated because the class has a user-declared copy constructor,
9261/// copy assignment operator, or destructor.
9262static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9263 SourceLocation UseLoc) {
9264 assert(CopyOp->isImplicit());
9265
9266 CXXRecordDecl *RD = CopyOp->getParent();
9267 CXXMethodDecl *UserDeclaredOperation = 0;
9268
9269 // In Microsoft mode, assignment operations don't affect constructors and
9270 // vice versa.
9271 if (RD->hasUserDeclaredDestructor()) {
9272 UserDeclaredOperation = RD->getDestructor();
9273 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9274 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009275 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009276 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009277 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009278 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009279 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009280 break;
9281 }
9282 }
9283 assert(UserDeclaredOperation);
9284 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9285 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009286 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009287 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009288 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009289 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009290 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009291 break;
9292 }
9293 }
9294 assert(UserDeclaredOperation);
9295 }
9296
9297 if (UserDeclaredOperation) {
9298 S.Diag(UserDeclaredOperation->getLocation(),
9299 diag::warn_deprecated_copy_operation)
9300 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9301 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9302 S.Diag(UseLoc, diag::note_member_synthesized_at)
9303 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9304 : Sema::CXXCopyAssignment)
9305 << RD;
9306 }
9307}
9308
Douglas Gregorb139cd52010-05-01 20:49:11 +00009309void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9310 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009311 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009312 CopyAssignOperator->isOverloadedOperator() &&
9313 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009314 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9315 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009316 "DefineImplicitCopyAssignment called for wrong function");
9317
9318 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9319
9320 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9321 CopyAssignOperator->setInvalidDecl();
9322 return;
9323 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009324
9325 // C++11 [class.copy]p18:
9326 // The [definition of an implicitly declared copy assignment operator] is
9327 // deprecated if the class has a user-declared copy constructor or a
9328 // user-declared destructor.
9329 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9330 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9331
Eli Friedman276dd182013-09-05 00:02:25 +00009332 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009333
Eli Friedmaneaf34142012-10-18 20:14:08 +00009334 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009335 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009336
9337 // C++0x [class.copy]p30:
9338 // The implicitly-defined or explicitly-defaulted copy assignment operator
9339 // for a non-union class X performs memberwise copy assignment of its
9340 // subobjects. The direct base classes of X are assigned first, in the
9341 // order of their declaration in the base-specifier-list, and then the
9342 // immediate non-static data members of X are assigned, in the order in
9343 // which they were declared in the class definition.
9344
9345 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009346 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009347
9348 // The parameter for the "other" object, which we are copying from.
9349 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9350 Qualifiers OtherQuals = Other->getType().getQualifiers();
9351 QualType OtherRefType = Other->getType();
9352 if (const LValueReferenceType *OtherRef
9353 = OtherRefType->getAs<LValueReferenceType>()) {
9354 OtherRefType = OtherRef->getPointeeType();
9355 OtherQuals = OtherRefType.getQualifiers();
9356 }
9357
9358 // Our location for everything implicitly-generated.
9359 SourceLocation Loc = CopyAssignOperator->getLocation();
9360
Pavel Labath58934982013-08-30 08:52:28 +00009361 // Builds a DeclRefExpr for the "other" object.
9362 RefBuilder OtherRef(Other, OtherRefType);
9363
9364 // Builds the "this" pointer.
9365 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009366
9367 // Assign base classes.
9368 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009369 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009370 // Form the assignment:
9371 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009372 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009373 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009374 Invalid = true;
9375 continue;
9376 }
9377
John McCallcf142162010-08-07 06:22:56 +00009378 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009379 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009380
Douglas Gregorb139cd52010-05-01 20:49:11 +00009381 // Construct the "from" expression, which is an implicit cast to the
9382 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009383 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9384 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009385
9386 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009387 DerefBuilder DerefThis(This);
9388 CastBuilder To(DerefThis,
9389 Context.getCVRQualifiedType(
9390 BaseType, CopyAssignOperator->getTypeQualifiers()),
9391 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009392
9393 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009394 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009395 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009396 /*CopyingBaseSubobject=*/true,
9397 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009398 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009399 Diag(CurrentLocation, diag::note_member_synthesized_at)
9400 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9401 CopyAssignOperator->setInvalidDecl();
9402 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403 }
9404
9405 // Success! Record the copy.
9406 Statements.push_back(Copy.takeAs<Expr>());
9407 }
9408
Douglas Gregorb139cd52010-05-01 20:49:11 +00009409 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009410 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009411 if (Field->isUnnamedBitfield())
9412 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009413
9414 if (Field->isInvalidDecl()) {
9415 Invalid = true;
9416 continue;
9417 }
9418
Douglas Gregorb139cd52010-05-01 20:49:11 +00009419 // Check for members of reference type; we can't copy those.
9420 if (Field->getType()->isReferenceType()) {
9421 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9422 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9423 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009424 Diag(CurrentLocation, diag::note_member_synthesized_at)
9425 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009426 Invalid = true;
9427 continue;
9428 }
9429
9430 // Check for members of const-qualified, non-class type.
9431 QualType BaseType = Context.getBaseElementType(Field->getType());
9432 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9433 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9434 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9435 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009436 Diag(CurrentLocation, diag::note_member_synthesized_at)
9437 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438 Invalid = true;
9439 continue;
9440 }
John McCall1b1a1db2011-06-17 00:18:42 +00009441
9442 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009443 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9444 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009445
9446 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009447 if (FieldType->isIncompleteArrayType()) {
9448 assert(ClassDecl->hasFlexibleArrayMember() &&
9449 "Incomplete array type is not valid");
9450 continue;
9451 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009452
9453 // Build references to the field in the object we're copying from and to.
9454 CXXScopeSpec SS; // Intentionally empty
9455 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9456 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009457 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009458 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009459
9460 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9461
9462 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009463
Douglas Gregorb139cd52010-05-01 20:49:11 +00009464 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009465 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009466 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009467 /*CopyingBaseSubobject=*/false,
9468 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009469 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009470 Diag(CurrentLocation, diag::note_member_synthesized_at)
9471 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9472 CopyAssignOperator->setInvalidDecl();
9473 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009474 }
9475
9476 // Success! Record the copy.
9477 Statements.push_back(Copy.takeAs<Stmt>());
9478 }
9479
9480 if (!Invalid) {
9481 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009482 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009483
John McCalldadc5752010-08-24 06:29:42 +00009484 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009485 if (Return.isInvalid())
9486 Invalid = true;
9487 else {
9488 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009489
9490 if (Trap.hasErrorOccurred()) {
9491 Diag(CurrentLocation, diag::note_member_synthesized_at)
9492 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9493 Invalid = true;
9494 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009495 }
9496 }
9497
9498 if (Invalid) {
9499 CopyAssignOperator->setInvalidDecl();
9500 return;
9501 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009502
9503 StmtResult Body;
9504 {
9505 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009506 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009507 /*isStmtExpr=*/false);
9508 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9509 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009510 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009511
9512 if (ASTMutationListener *L = getASTMutationListener()) {
9513 L->CompletedImplicitDefinition(CopyAssignOperator);
9514 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009515}
9516
Sebastian Redl22653ba2011-08-30 19:58:05 +00009517Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009518Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9519 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009520
Richard Smithd3b5c9082012-07-27 04:22:15 +00009521 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009522 if (ClassDecl->isInvalidDecl())
9523 return ExceptSpec;
9524
9525 // C++0x [except.spec]p14:
9526 // An implicitly declared special member function (Clause 12) shall have an
9527 // exception-specification. [...]
9528
9529 // It is unspecified whether or not an implicit move assignment operator
9530 // attempts to deduplicate calls to assignment operators of virtual bases are
9531 // made. As such, this exception specification is effectively unspecified.
9532 // Based on a similar decision made for constness in C++0x, we're erring on
9533 // the side of assuming such calls to be made regardless of whether they
9534 // actually happen.
9535 // Note that a move constructor is not implicitly declared when there are
9536 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009537 for (const auto &Base : ClassDecl->bases()) {
9538 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009539 continue;
9540
9541 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009542 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009543 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009544 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009545 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009546 }
9547
Aaron Ballman445a9392014-03-13 16:15:17 +00009548 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009549 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009550 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009551 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009552 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009553 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009554 }
9555
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009556 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009557 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009558 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009559 if (CXXMethodDecl *MoveAssign =
9560 LookupMovingAssignment(FieldClassDecl,
9561 FieldType.getCVRQualifiers(),
9562 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009563 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009564 }
9565 }
9566
9567 return ExceptSpec;
9568}
9569
9570CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009571 assert(ClassDecl->needsImplicitMoveAssignment());
9572
Richard Smith8bf22e52012-11-29 01:34:07 +00009573 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9574 if (DSM.isAlreadyBeingDeclared())
9575 return 0;
9576
Sebastian Redl22653ba2011-08-30 19:58:05 +00009577 // Note: The following rules are largely analoguous to the move
9578 // constructor rules.
9579
Sebastian Redl22653ba2011-08-30 19:58:05 +00009580 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9581 QualType RetType = Context.getLValueReferenceType(ArgType);
9582 ArgType = Context.getRValueReferenceType(ArgType);
9583
Richard Smith99005e62013-05-07 03:19:20 +00009584 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9585 CXXMoveAssignment,
9586 false);
9587
Sebastian Redl22653ba2011-08-30 19:58:05 +00009588 // An implicitly-declared move assignment operator is an inline public
9589 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009590 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9591 SourceLocation ClassLoc = ClassDecl->getLocation();
9592 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009593 CXXMethodDecl *MoveAssignment =
9594 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9595 /*TInfo=*/0, /*StorageClass=*/SC_None,
9596 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009597 MoveAssignment->setAccess(AS_public);
9598 MoveAssignment->setDefaulted();
9599 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009600
Richard Smithd3b5c9082012-07-27 04:22:15 +00009601 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009602 FunctionProtoType::ExtProtoInfo EPI =
9603 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009604 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009605
Sebastian Redl22653ba2011-08-30 19:58:05 +00009606 // Add the parameter to the operator.
9607 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9608 ClassLoc, ClassLoc, /*Id=*/0,
9609 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009610 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009611 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009612
Richard Smith6b02d462012-12-08 08:32:28 +00009613 AddOverriddenMethods(ClassDecl, MoveAssignment);
9614
9615 MoveAssignment->setTrivial(
9616 ClassDecl->needsOverloadResolutionForMoveAssignment()
9617 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9618 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009619
Richard Smithd951a1d2012-02-18 02:02:13 +00009620 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009621 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9622 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009623 }
9624
Richard Smith6b02d462012-12-08 08:32:28 +00009625 // Note that we have added this copy-assignment operator.
9626 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9627
Sebastian Redl22653ba2011-08-30 19:58:05 +00009628 if (Scope *S = getScopeForContext(ClassDecl))
9629 PushOnScopeChains(MoveAssignment, S, false);
9630 ClassDecl->addDecl(MoveAssignment);
9631
Sebastian Redl22653ba2011-08-30 19:58:05 +00009632 return MoveAssignment;
9633}
9634
Richard Smithb2504bd2013-11-04 04:26:14 +00009635/// Check if we're implicitly defining a move assignment operator for a class
9636/// with virtual bases. Such a move assignment might move-assign the virtual
9637/// base multiple times.
9638static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9639 SourceLocation CurrentLocation) {
9640 assert(!Class->isDependentContext() && "should not define dependent move");
9641
9642 // Only a virtual base could get implicitly move-assigned multiple times.
9643 // Only a non-trivial move assignment can observe this. We only want to
9644 // diagnose if we implicitly define an assignment operator that assigns
9645 // two base classes, both of which move-assign the same virtual base.
9646 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9647 Class->getNumBases() < 2)
9648 return;
9649
9650 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9651 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9652 VBaseMap VBases;
9653
Aaron Ballman574705e2014-03-13 15:41:46 +00009654 for (auto &BI : Class->bases()) {
9655 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009656 while (!Worklist.empty()) {
9657 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9658 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9659
9660 // If the base has no non-trivial move assignment operators,
9661 // we don't care about moves from it.
9662 if (!Base->hasNonTrivialMoveAssignment())
9663 continue;
9664
9665 // If there's nothing virtual here, skip it.
9666 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9667 continue;
9668
9669 // If we're not actually going to call a move assignment for this base,
9670 // or the selected move assignment is trivial, skip it.
9671 Sema::SpecialMemberOverloadResult *SMOR =
9672 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9673 /*ConstArg*/false, /*VolatileArg*/false,
9674 /*RValueThis*/true, /*ConstThis*/false,
9675 /*VolatileThis*/false);
9676 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9677 !SMOR->getMethod()->isMoveAssignmentOperator())
9678 continue;
9679
9680 if (BaseSpec->isVirtual()) {
9681 // We're going to move-assign this virtual base, and its move
9682 // assignment operator is not trivial. If this can happen for
9683 // multiple distinct direct bases of Class, diagnose it. (If it
9684 // only happens in one base, we'll diagnose it when synthesizing
9685 // that base class's move assignment operator.)
9686 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009687 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009688 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009689 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009690 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9691 << Class << Base;
9692 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9693 << (Base->getCanonicalDecl() ==
9694 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9695 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009696 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009697 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009698 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9699 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009700
9701 // Only diagnose each vbase once.
9702 Existing = 0;
9703 }
9704 } else {
9705 // Only walk over bases that have defaulted move assignment operators.
9706 // We assume that any user-provided move assignment operator handles
9707 // the multiple-moves-of-vbase case itself somehow.
9708 if (!SMOR->getMethod()->isDefaulted())
9709 continue;
9710
9711 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009712 for (auto &BI : Base->bases())
9713 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009714 }
9715 }
9716 }
9717}
9718
Sebastian Redl22653ba2011-08-30 19:58:05 +00009719void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9720 CXXMethodDecl *MoveAssignOperator) {
9721 assert((MoveAssignOperator->isDefaulted() &&
9722 MoveAssignOperator->isOverloadedOperator() &&
9723 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009724 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9725 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009726 "DefineImplicitMoveAssignment called for wrong function");
9727
9728 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9729
9730 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9731 MoveAssignOperator->setInvalidDecl();
9732 return;
9733 }
9734
Eli Friedman276dd182013-09-05 00:02:25 +00009735 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009736
Eli Friedmaneaf34142012-10-18 20:14:08 +00009737 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009738 DiagnosticErrorTrap Trap(Diags);
9739
9740 // C++0x [class.copy]p28:
9741 // The implicitly-defined or move assignment operator for a non-union class
9742 // X performs memberwise move assignment of its subobjects. The direct base
9743 // classes of X are assigned first, in the order of their declaration in the
9744 // base-specifier-list, and then the immediate non-static data members of X
9745 // are assigned, in the order in which they were declared in the class
9746 // definition.
9747
Richard Smithb2504bd2013-11-04 04:26:14 +00009748 // Issue a warning if our implicit move assignment operator will move
9749 // from a virtual base more than once.
9750 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009751
Sebastian Redl22653ba2011-08-30 19:58:05 +00009752 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009753 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009754
9755 // The parameter for the "other" object, which we are move from.
9756 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9757 QualType OtherRefType = Other->getType()->
9758 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009759 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009760 "Bad argument type of defaulted move assignment");
9761
9762 // Our location for everything implicitly-generated.
9763 SourceLocation Loc = MoveAssignOperator->getLocation();
9764
Pavel Labath58934982013-08-30 08:52:28 +00009765 // Builds a reference to the "other" object.
9766 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009767 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009768 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009769
Pavel Labath58934982013-08-30 08:52:28 +00009770 // Builds the "this" pointer.
9771 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009772
Sebastian Redl22653ba2011-08-30 19:58:05 +00009773 // Assign base classes.
9774 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009775 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009776 // C++11 [class.copy]p28:
9777 // It is unspecified whether subobjects representing virtual base classes
9778 // are assigned more than once by the implicitly-defined copy assignment
9779 // operator.
9780 // FIXME: Do not assign to a vbase that will be assigned by some other base
9781 // class. For a move-assignment, this can result in the vbase being moved
9782 // multiple times.
9783
Sebastian Redl22653ba2011-08-30 19:58:05 +00009784 // Form the assignment:
9785 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009786 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009787 if (!BaseType->isRecordType()) {
9788 Invalid = true;
9789 continue;
9790 }
9791
9792 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009793 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009794
9795 // Construct the "from" expression, which is an implicit cast to the
9796 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009797 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009798
9799 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009800 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009801
9802 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009803 CastBuilder To(DerefThis,
9804 Context.getCVRQualifiedType(
9805 BaseType, MoveAssignOperator->getTypeQualifiers()),
9806 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009807
9808 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009809 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009810 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009811 /*CopyingBaseSubobject=*/true,
9812 /*Copying=*/false);
9813 if (Move.isInvalid()) {
9814 Diag(CurrentLocation, diag::note_member_synthesized_at)
9815 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9816 MoveAssignOperator->setInvalidDecl();
9817 return;
9818 }
9819
9820 // Success! Record the move.
9821 Statements.push_back(Move.takeAs<Expr>());
9822 }
9823
Sebastian Redl22653ba2011-08-30 19:58:05 +00009824 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009825 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009826 if (Field->isUnnamedBitfield())
9827 continue;
9828
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009829 if (Field->isInvalidDecl()) {
9830 Invalid = true;
9831 continue;
9832 }
9833
Sebastian Redl22653ba2011-08-30 19:58:05 +00009834 // Check for members of reference type; we can't move those.
9835 if (Field->getType()->isReferenceType()) {
9836 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9837 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9838 Diag(Field->getLocation(), diag::note_declared_at);
9839 Diag(CurrentLocation, diag::note_member_synthesized_at)
9840 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9841 Invalid = true;
9842 continue;
9843 }
9844
9845 // Check for members of const-qualified, non-class type.
9846 QualType BaseType = Context.getBaseElementType(Field->getType());
9847 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9848 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9849 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9850 Diag(Field->getLocation(), diag::note_declared_at);
9851 Diag(CurrentLocation, diag::note_member_synthesized_at)
9852 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9853 Invalid = true;
9854 continue;
9855 }
9856
9857 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009858 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9859 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009860
9861 QualType FieldType = Field->getType().getNonReferenceType();
9862 if (FieldType->isIncompleteArrayType()) {
9863 assert(ClassDecl->hasFlexibleArrayMember() &&
9864 "Incomplete array type is not valid");
9865 continue;
9866 }
9867
9868 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009869 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9870 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009871 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009873 MemberBuilder From(MoveOther, OtherRefType,
9874 /*IsArrow=*/false, MemberLookup);
9875 MemberBuilder To(This, getCurrentThisType(),
9876 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009877
Pavel Labath58934982013-08-30 08:52:28 +00009878 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009879 "Member reference with rvalue base must be rvalue except for reference "
9880 "members, which aren't allowed for move assignment.");
9881
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009883 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009884 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009885 /*CopyingBaseSubobject=*/false,
9886 /*Copying=*/false);
9887 if (Move.isInvalid()) {
9888 Diag(CurrentLocation, diag::note_member_synthesized_at)
9889 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9890 MoveAssignOperator->setInvalidDecl();
9891 return;
9892 }
Richard Smith11d19592012-11-12 23:33:00 +00009893
Sebastian Redl22653ba2011-08-30 19:58:05 +00009894 // Success! Record the copy.
9895 Statements.push_back(Move.takeAs<Stmt>());
9896 }
9897
9898 if (!Invalid) {
9899 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009900 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009901
9902 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9903 if (Return.isInvalid())
9904 Invalid = true;
9905 else {
9906 Statements.push_back(Return.takeAs<Stmt>());
9907
9908 if (Trap.hasErrorOccurred()) {
9909 Diag(CurrentLocation, diag::note_member_synthesized_at)
9910 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9911 Invalid = true;
9912 }
9913 }
9914 }
9915
9916 if (Invalid) {
9917 MoveAssignOperator->setInvalidDecl();
9918 return;
9919 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009920
9921 StmtResult Body;
9922 {
9923 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009924 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009925 /*isStmtExpr=*/false);
9926 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9927 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009928 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9929
9930 if (ASTMutationListener *L = getASTMutationListener()) {
9931 L->CompletedImplicitDefinition(MoveAssignOperator);
9932 }
9933}
9934
Richard Smithd3b5c9082012-07-27 04:22:15 +00009935Sema::ImplicitExceptionSpecification
9936Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9937 CXXRecordDecl *ClassDecl = MD->getParent();
9938
9939 ImplicitExceptionSpecification ExceptSpec(*this);
9940 if (ClassDecl->isInvalidDecl())
9941 return ExceptSpec;
9942
9943 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009944 assert(T->getNumParams() >= 1 && "not a copy ctor");
9945 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009946
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009947 // C++ [except.spec]p14:
9948 // An implicitly declared special member function (Clause 12) shall have an
9949 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +00009950 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009951 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +00009952 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009953 continue;
9954
Douglas Gregora6d69502010-07-02 23:41:54 +00009955 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009956 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009957 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009958 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +00009959 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009960 }
Aaron Ballman445a9392014-03-13 16:15:17 +00009961 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00009962 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009963 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009964 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009965 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +00009966 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009967 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009968 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009969 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00009970 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9971 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +00009972 LookupCopyingConstructor(FieldClassDecl,
9973 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +00009974 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009975 }
9976 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009977
Richard Smithd3b5c9082012-07-27 04:22:15 +00009978 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +00009979}
9980
9981CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9982 CXXRecordDecl *ClassDecl) {
9983 // C++ [class.copy]p4:
9984 // If the class definition does not explicitly declare a copy
9985 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +00009986 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +00009987
Richard Smith8bf22e52012-11-29 01:34:07 +00009988 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9989 if (DSM.isAlreadyBeingDeclared())
9990 return 0;
9991
Alexis Hunt913820d2011-05-13 06:10:58 +00009992 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9993 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +00009994 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +00009995 if (Const)
9996 ArgType = ArgType.withConst();
9997 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +00009998
Richard Smithb5800092012-06-10 05:43:50 +00009999 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10000 CXXCopyConstructor,
10001 Const);
10002
Douglas Gregor54be3392010-07-01 17:57:27 +000010003 DeclarationName Name
10004 = Context.DeclarationNames.getCXXConstructorName(
10005 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010006 SourceLocation ClassLoc = ClassDecl->getLocation();
10007 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010008
10009 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010010 // member of its class.
10011 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010012 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010013 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010014 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010015 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010016 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010017
Richard Smithd3b5c9082012-07-27 04:22:15 +000010018 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010019 FunctionProtoType::ExtProtoInfo EPI =
10020 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010021 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010022 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010023
Douglas Gregor54be3392010-07-01 17:57:27 +000010024 // Add the parameter to the constructor.
10025 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010026 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010027 /*IdentifierInfo=*/0,
10028 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010029 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010030 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010031
Richard Smith6b02d462012-12-08 08:32:28 +000010032 CopyConstructor->setTrivial(
10033 ClassDecl->needsOverloadResolutionForCopyConstructor()
10034 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10035 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010036
Richard Smith852265f2012-03-30 20:53:28 +000010037 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010038 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010039
Richard Smith6b02d462012-12-08 08:32:28 +000010040 // Note that we have declared this constructor.
10041 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10042
10043 if (Scope *S = getScopeForContext(ClassDecl))
10044 PushOnScopeChains(CopyConstructor, S, false);
10045 ClassDecl->addDecl(CopyConstructor);
10046
Douglas Gregor54be3392010-07-01 17:57:27 +000010047 return CopyConstructor;
10048}
10049
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010050void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010051 CXXConstructorDecl *CopyConstructor) {
10052 assert((CopyConstructor->isDefaulted() &&
10053 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010054 !CopyConstructor->doesThisDeclarationHaveABody() &&
10055 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010056 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010057
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010058 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010059 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010060
Richard Smithd577fbb2013-06-13 03:23:42 +000010061 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010062 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010063 // deprecated if the class has a user-declared copy assignment operator
10064 // or a user-declared destructor.
10065 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10066 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10067
Eli Friedmaneaf34142012-10-18 20:14:08 +000010068 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010069 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010070
David Blaikie3fc2f912013-01-17 05:26:25 +000010071 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010072 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010073 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010074 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010075 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010076 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010077 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010078 CopyConstructor->setBody(ActOnCompoundStmt(
10079 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10080 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010081 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010082
Eli Friedman276dd182013-09-05 00:02:25 +000010083 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010084 if (ASTMutationListener *L = getASTMutationListener()) {
10085 L->CompletedImplicitDefinition(CopyConstructor);
10086 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010087}
10088
Sebastian Redl22653ba2011-08-30 19:58:05 +000010089Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010090Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10091 CXXRecordDecl *ClassDecl = MD->getParent();
10092
Sebastian Redl22653ba2011-08-30 19:58:05 +000010093 // C++ [except.spec]p14:
10094 // An implicitly declared special member function (Clause 12) shall have an
10095 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010096 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010097 if (ClassDecl->isInvalidDecl())
10098 return ExceptSpec;
10099
10100 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010101 for (const auto &B : ClassDecl->bases()) {
10102 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010103 continue;
10104
Aaron Ballman574705e2014-03-13 15:41:46 +000010105 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010106 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010107 CXXConstructorDecl *Constructor =
10108 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010109 // If this is a deleted function, add it anyway. This might be conformant
10110 // with the standard. This might not. I'm not sure. It might not matter.
10111 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010112 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010113 }
10114 }
10115
10116 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010117 for (const auto &B : ClassDecl->vbases()) {
10118 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010119 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010120 CXXConstructorDecl *Constructor =
10121 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010122 // If this is a deleted function, add it anyway. This might be conformant
10123 // with the standard. This might not. I'm not sure. It might not matter.
10124 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010125 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010126 }
10127 }
10128
10129 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010130 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010131 QualType FieldType = Context.getBaseElementType(F->getType());
10132 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10133 CXXConstructorDecl *Constructor =
10134 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010135 // If this is a deleted function, add it anyway. This might be conformant
10136 // with the standard. This might not. I'm not sure. It might not matter.
10137 // In particular, the problem is that this function never gets called. It
10138 // might just be ill-formed because this function attempts to refer to
10139 // a deleted function here.
10140 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010141 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010142 }
10143 }
10144
10145 return ExceptSpec;
10146}
10147
10148CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10149 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010150 assert(ClassDecl->needsImplicitMoveConstructor());
10151
Richard Smith8bf22e52012-11-29 01:34:07 +000010152 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10153 if (DSM.isAlreadyBeingDeclared())
10154 return 0;
10155
Sebastian Redl22653ba2011-08-30 19:58:05 +000010156 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10157 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010158
Richard Smithb5800092012-06-10 05:43:50 +000010159 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10160 CXXMoveConstructor,
10161 false);
10162
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163 DeclarationName Name
10164 = Context.DeclarationNames.getCXXConstructorName(
10165 Context.getCanonicalType(ClassType));
10166 SourceLocation ClassLoc = ClassDecl->getLocation();
10167 DeclarationNameInfo NameInfo(Name, ClassLoc);
10168
Richard Smith99005e62013-05-07 03:19:20 +000010169 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010170 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010171 // member of its class.
10172 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010173 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010174 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010175 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010176 MoveConstructor->setAccess(AS_public);
10177 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010178
Richard Smithd3b5c9082012-07-27 04:22:15 +000010179 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010180 FunctionProtoType::ExtProtoInfo EPI =
10181 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010182 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010183 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010184
Sebastian Redl22653ba2011-08-30 19:58:05 +000010185 // Add the parameter to the constructor.
10186 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10187 ClassLoc, ClassLoc,
10188 /*IdentifierInfo=*/0,
10189 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010190 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010191 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010192
Richard Smith6b02d462012-12-08 08:32:28 +000010193 MoveConstructor->setTrivial(
10194 ClassDecl->needsOverloadResolutionForMoveConstructor()
10195 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10196 : ClassDecl->hasTrivialMoveConstructor());
10197
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010198 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010199 ClassDecl->setImplicitMoveConstructorIsDeleted();
10200 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010201 }
10202
10203 // Note that we have declared this constructor.
10204 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10205
10206 if (Scope *S = getScopeForContext(ClassDecl))
10207 PushOnScopeChains(MoveConstructor, S, false);
10208 ClassDecl->addDecl(MoveConstructor);
10209
10210 return MoveConstructor;
10211}
10212
10213void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10214 CXXConstructorDecl *MoveConstructor) {
10215 assert((MoveConstructor->isDefaulted() &&
10216 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010217 !MoveConstructor->doesThisDeclarationHaveABody() &&
10218 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010219 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10220
10221 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10222 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10223
Eli Friedmaneaf34142012-10-18 20:14:08 +000010224 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225 DiagnosticErrorTrap Trap(Diags);
10226
David Blaikie3fc2f912013-01-17 05:26:25 +000010227 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 Trap.hasErrorOccurred()) {
10229 Diag(CurrentLocation, diag::note_member_synthesized_at)
10230 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10231 MoveConstructor->setInvalidDecl();
10232 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010233 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010234 MoveConstructor->setBody(ActOnCompoundStmt(
10235 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10236 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010237 }
10238
Eli Friedman276dd182013-09-05 00:02:25 +000010239 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010240
10241 if (ASTMutationListener *L = getASTMutationListener()) {
10242 L->CompletedImplicitDefinition(MoveConstructor);
10243 }
10244}
10245
Douglas Gregor74f7d502012-02-15 19:33:52 +000010246bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010247 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010248}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010249
10250void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010251 SourceLocation CurrentLocation,
10252 CXXConversionDecl *Conv) {
10253 CXXRecordDecl *Lambda = Conv->getParent();
10254 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10255 // If we are defining a specialization of a conversion to function-ptr
10256 // cache the deduced template arguments for this specialization
10257 // so that we can use them to retrieve the corresponding call-operator
10258 // and static-invoker.
10259 const TemplateArgumentList *DeducedTemplateArgs = 0;
10260
Douglas Gregor355efbb2012-02-17 03:02:34 +000010261
Faisal Vali571df122013-09-29 08:45:24 +000010262 // Retrieve the corresponding call-operator specialization.
10263 if (Lambda->isGenericLambda()) {
10264 assert(Conv->isFunctionTemplateSpecialization());
10265 FunctionTemplateDecl *CallOpTemplate =
10266 CallOp->getDescribedFunctionTemplate();
10267 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10268 void *InsertPos = 0;
10269 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10270 DeducedTemplateArgs->data(),
10271 DeducedTemplateArgs->size(),
10272 InsertPos);
10273 assert(CallOpSpec &&
10274 "Conversion operator must have a corresponding call operator");
10275 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10276 }
10277 // Mark the call operator referenced (and add to pending instantiations
10278 // if necessary).
10279 // For both the conversion and static-invoker template specializations
10280 // we construct their body's in this function, so no need to add them
10281 // to the PendingInstantiations.
10282 MarkFunctionReferenced(CurrentLocation, CallOp);
10283
Eli Friedmaneaf34142012-10-18 20:14:08 +000010284 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010285 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010286
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010287 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010288 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10289 // ... and get the corresponding specialization for a generic lambda.
10290 if (Lambda->isGenericLambda()) {
10291 assert(DeducedTemplateArgs &&
10292 "Must have deduced template arguments from Conversion Operator");
10293 FunctionTemplateDecl *InvokeTemplate =
10294 Invoker->getDescribedFunctionTemplate();
10295 void *InsertPos = 0;
10296 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10297 DeducedTemplateArgs->data(),
10298 DeducedTemplateArgs->size(),
10299 InsertPos);
10300 assert(InvokeSpec &&
10301 "Must have a corresponding static invoker specialization");
10302 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10303 }
10304 // Construct the body of the conversion function { return __invoke; }.
10305 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10306 VK_LValue, Conv->getLocation()).take();
10307 assert(FunctionRef && "Can't refer to __invoke function?");
10308 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10309 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10310 Conv->getLocation(),
10311 Conv->getLocation()));
10312
10313 Conv->markUsed(Context);
10314 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010315
Faisal Vali571df122013-09-29 08:45:24 +000010316 // Fill in the __invoke function with a dummy implementation. IR generation
10317 // will fill in the actual details.
10318 Invoker->markUsed(Context);
10319 Invoker->setReferenced();
10320 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10321
Douglas Gregord3b672c2012-02-16 01:06:16 +000010322 if (ASTMutationListener *L = getASTMutationListener()) {
10323 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010324 L->CompletedImplicitDefinition(Invoker);
10325 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010326}
10327
Faisal Vali571df122013-09-29 08:45:24 +000010328
10329
Douglas Gregord3b672c2012-02-16 01:06:16 +000010330void Sema::DefineImplicitLambdaToBlockPointerConversion(
10331 SourceLocation CurrentLocation,
10332 CXXConversionDecl *Conv)
10333{
Faisal Vali850da1a2013-09-29 17:08:32 +000010334 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010335
Eli Friedman276dd182013-09-05 00:02:25 +000010336 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010337
Eli Friedmaneaf34142012-10-18 20:14:08 +000010338 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010339 DiagnosticErrorTrap Trap(Diags);
10340
Douglas Gregored90df32012-02-22 05:02:47 +000010341 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010342 Expr *This = ActOnCXXThis(CurrentLocation).take();
10343 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010344
Eli Friedman98b01ed2012-03-01 04:01:32 +000010345 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10346 Conv->getLocation(),
10347 Conv, DerefThis);
10348
10349 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10350 // behavior. Note that only the general conversion function does this
10351 // (since it's unusable otherwise); in the case where we inline the
10352 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010353 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010354 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10355 CK_CopyAndAutoreleaseBlockObject,
10356 BuildBlock.get(), 0, VK_RValue);
10357
10358 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010359 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010360 Conv->setInvalidDecl();
10361 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010362 }
Douglas Gregored90df32012-02-22 05:02:47 +000010363
Douglas Gregored90df32012-02-22 05:02:47 +000010364 // Create the return statement that returns the block from the conversion
10365 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010366 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010367 if (Return.isInvalid()) {
10368 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10369 Conv->setInvalidDecl();
10370 return;
10371 }
10372
10373 // Set the body of the conversion function.
10374 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010375 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010376 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010377 Conv->getLocation()));
10378
Douglas Gregored90df32012-02-22 05:02:47 +000010379 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010380 if (ASTMutationListener *L = getASTMutationListener()) {
10381 L->CompletedImplicitDefinition(Conv);
10382 }
10383}
10384
Douglas Gregord2f70072012-03-10 06:53:13 +000010385/// \brief Determine whether the given list arguments contains exactly one
10386/// "real" (non-default) argument.
10387static bool hasOneRealArgument(MultiExprArg Args) {
10388 switch (Args.size()) {
10389 case 0:
10390 return false;
10391
10392 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010393 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010394 return false;
10395
10396 // fall through
10397 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010398 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010399 }
10400
10401 return false;
10402}
10403
John McCalldadc5752010-08-24 06:29:42 +000010404ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010405Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010406 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010407 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010408 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010409 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010410 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010411 unsigned ConstructKind,
10412 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010413 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010414
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010415 // C++0x [class.copy]p34:
10416 // When certain criteria are met, an implementation is allowed to
10417 // omit the copy/move construction of a class object, even if the
10418 // copy/move constructor and/or destructor for the object have
10419 // side effects. [...]
10420 // - when a temporary class object that has not been bound to a
10421 // reference (12.2) would be copied/moved to a class object
10422 // with the same cv-unqualified type, the copy/move operation
10423 // can be omitted by constructing the temporary object
10424 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010425 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010426 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010427 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010428 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010429 }
Mike Stump11289f42009-09-09 15:08:12 +000010430
10431 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010432 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010433 IsListInitialization, RequiresZeroInit,
10434 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010435}
10436
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010437/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10438/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010439ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010440Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10441 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010442 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010443 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010444 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010445 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010446 unsigned ConstructKind,
10447 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010448 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010449 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010450 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010451 HadMultipleCandidates,
10452 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010453 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10454 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010455}
10456
John McCall03c48482010-02-02 09:10:11 +000010457void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010458 if (VD->isInvalidDecl()) return;
10459
John McCall03c48482010-02-02 09:10:11 +000010460 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010461 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010462 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010463 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010464
Chandler Carruth86d17d32011-03-27 21:26:48 +000010465 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010466 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010467 CheckDestructorAccess(VD->getLocation(), Destructor,
10468 PDiag(diag::err_access_dtor_var)
10469 << VD->getDeclName()
10470 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010471 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010472
Chandler Carruth86d17d32011-03-27 21:26:48 +000010473 if (!VD->hasGlobalStorage()) return;
10474
10475 // Emit warning for non-trivial dtor in global scope (a real global,
10476 // class-static, function-static).
10477 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10478
10479 // TODO: this should be re-enabled for static locals by !CXAAtExit
10480 if (!VD->isStaticLocal())
10481 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010482}
10483
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010484/// \brief Given a constructor and the set of arguments provided for the
10485/// constructor, convert the arguments and add any required default arguments
10486/// to form a proper call to this constructor.
10487///
10488/// \returns true if an error occurred, false otherwise.
10489bool
10490Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10491 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010492 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010493 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010494 bool AllowExplicit,
10495 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010496 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10497 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010498 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010499
10500 const FunctionProtoType *Proto
10501 = Constructor->getType()->getAs<FunctionProtoType>();
10502 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010503 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010504
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010505 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010506 if (NumArgs < NumParams)
10507 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010508 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010509 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010510
10511 VariadicCallType CallType =
10512 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010513 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010514 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010515 Proto, 0,
10516 llvm::makeArrayRef(Args, NumArgs),
10517 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010518 CallType, AllowExplicit,
10519 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010520 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010521
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010522 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010523
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010524 CheckConstructorCall(Constructor,
10525 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10526 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010527 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010528
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010529 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010530}
10531
Anders Carlssone363c8e2009-12-12 00:32:00 +000010532static inline bool
10533CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10534 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010535 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010536 if (isa<NamespaceDecl>(DC)) {
10537 return SemaRef.Diag(FnDecl->getLocation(),
10538 diag::err_operator_new_delete_declared_in_namespace)
10539 << FnDecl->getDeclName();
10540 }
10541
10542 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010543 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010544 return SemaRef.Diag(FnDecl->getLocation(),
10545 diag::err_operator_new_delete_declared_static)
10546 << FnDecl->getDeclName();
10547 }
10548
Anders Carlsson60659a82009-12-12 02:43:16 +000010549 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010550}
10551
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010552static inline bool
10553CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10554 CanQualType ExpectedResultType,
10555 CanQualType ExpectedFirstParamType,
10556 unsigned DependentParamTypeDiag,
10557 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010558 QualType ResultType =
10559 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010560
10561 // Check that the result type is not dependent.
10562 if (ResultType->isDependentType())
10563 return SemaRef.Diag(FnDecl->getLocation(),
10564 diag::err_operator_new_delete_dependent_result_type)
10565 << FnDecl->getDeclName() << ExpectedResultType;
10566
10567 // Check that the result type is what we expect.
10568 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10569 return SemaRef.Diag(FnDecl->getLocation(),
10570 diag::err_operator_new_delete_invalid_result_type)
10571 << FnDecl->getDeclName() << ExpectedResultType;
10572
10573 // A function template must have at least 2 parameters.
10574 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10575 return SemaRef.Diag(FnDecl->getLocation(),
10576 diag::err_operator_new_delete_template_too_few_parameters)
10577 << FnDecl->getDeclName();
10578
10579 // The function decl must have at least 1 parameter.
10580 if (FnDecl->getNumParams() == 0)
10581 return SemaRef.Diag(FnDecl->getLocation(),
10582 diag::err_operator_new_delete_too_few_parameters)
10583 << FnDecl->getDeclName();
10584
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010585 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010586 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10587 if (FirstParamType->isDependentType())
10588 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10589 << FnDecl->getDeclName() << ExpectedFirstParamType;
10590
10591 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010592 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010593 ExpectedFirstParamType)
10594 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10595 << FnDecl->getDeclName() << ExpectedFirstParamType;
10596
10597 return false;
10598}
10599
Anders Carlsson12308f42009-12-11 23:23:22 +000010600static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010601CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010602 // C++ [basic.stc.dynamic.allocation]p1:
10603 // A program is ill-formed if an allocation function is declared in a
10604 // namespace scope other than global scope or declared static in global
10605 // scope.
10606 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10607 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010608
10609 CanQualType SizeTy =
10610 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10611
10612 // C++ [basic.stc.dynamic.allocation]p1:
10613 // The return type shall be void*. The first parameter shall have type
10614 // std::size_t.
10615 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10616 SizeTy,
10617 diag::err_operator_new_dependent_param_type,
10618 diag::err_operator_new_param_type))
10619 return true;
10620
10621 // C++ [basic.stc.dynamic.allocation]p1:
10622 // The first parameter shall not have an associated default argument.
10623 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010624 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010625 diag::err_operator_new_default_arg)
10626 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10627
10628 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010629}
10630
10631static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010632CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010633 // C++ [basic.stc.dynamic.deallocation]p1:
10634 // A program is ill-formed if deallocation functions are declared in a
10635 // namespace scope other than global scope or declared static in global
10636 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010637 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10638 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010639
10640 // C++ [basic.stc.dynamic.deallocation]p2:
10641 // Each deallocation function shall return void and its first parameter
10642 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010643 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10644 SemaRef.Context.VoidPtrTy,
10645 diag::err_operator_delete_dependent_param_type,
10646 diag::err_operator_delete_param_type))
10647 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010648
Anders Carlsson12308f42009-12-11 23:23:22 +000010649 return false;
10650}
10651
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010652/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10653/// of this overloaded operator is well-formed. If so, returns false;
10654/// otherwise, emits appropriate diagnostics and returns true.
10655bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010656 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010657 "Expected an overloaded operator declaration");
10658
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010659 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10660
Mike Stump11289f42009-09-09 15:08:12 +000010661 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010662 // The allocation and deallocation functions, operator new,
10663 // operator new[], operator delete and operator delete[], are
10664 // described completely in 3.7.3. The attributes and restrictions
10665 // found in the rest of this subclause do not apply to them unless
10666 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010667 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010668 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010669
Anders Carlsson22f443f2009-12-12 00:26:23 +000010670 if (Op == OO_New || Op == OO_Array_New)
10671 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010672
10673 // C++ [over.oper]p6:
10674 // An operator function shall either be a non-static member
10675 // function or be a non-member function and have at least one
10676 // parameter whose type is a class, a reference to a class, an
10677 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010678 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10679 if (MethodDecl->isStatic())
10680 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010681 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010682 } else {
10683 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010684 for (auto Param : FnDecl->params()) {
10685 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010686 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10687 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010688 ClassOrEnumParam = true;
10689 break;
10690 }
10691 }
10692
Douglas Gregord69246b2008-11-17 16:14:12 +000010693 if (!ClassOrEnumParam)
10694 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010695 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010696 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010697 }
10698
10699 // C++ [over.oper]p8:
10700 // An operator function cannot have default arguments (8.3.6),
10701 // except where explicitly stated below.
10702 //
Mike Stump11289f42009-09-09 15:08:12 +000010703 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010704 // (C++ [over.call]p1).
10705 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010706 for (auto Param : FnDecl->params()) {
10707 if (Param->hasDefaultArg())
10708 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010709 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010710 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010711 }
10712 }
10713
Douglas Gregor6cf08062008-11-10 13:38:07 +000010714 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10715 { false, false, false }
10716#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10717 , { Unary, Binary, MemberOnly }
10718#include "clang/Basic/OperatorKinds.def"
10719 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010720
Douglas Gregor6cf08062008-11-10 13:38:07 +000010721 bool CanBeUnaryOperator = OperatorUses[Op][0];
10722 bool CanBeBinaryOperator = OperatorUses[Op][1];
10723 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010724
10725 // C++ [over.oper]p8:
10726 // [...] Operator functions cannot have more or fewer parameters
10727 // than the number required for the corresponding operator, as
10728 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010729 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010730 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010731 if (Op != OO_Call &&
10732 ((NumParams == 1 && !CanBeUnaryOperator) ||
10733 (NumParams == 2 && !CanBeBinaryOperator) ||
10734 (NumParams < 1) || (NumParams > 2))) {
10735 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010736 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010737 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010738 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010739 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010740 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010741 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010742 assert(CanBeBinaryOperator &&
10743 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010744 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010745 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010746
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010747 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010748 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010749 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010750
Douglas Gregord69246b2008-11-17 16:14:12 +000010751 // Overloaded operators other than operator() cannot be variadic.
10752 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010753 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010754 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010755 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010756 }
10757
10758 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010759 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10760 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010761 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010762 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010763 }
10764
10765 // C++ [over.inc]p1:
10766 // The user-defined function called operator++ implements the
10767 // prefix and postfix ++ operator. If this function is a member
10768 // function with no parameters, or a non-member function with one
10769 // parameter of class or enumeration type, it defines the prefix
10770 // increment operator ++ for objects of that type. If the function
10771 // is a member function with one parameter (which shall be of type
10772 // int) or a non-member function with two parameters (the second
10773 // of which shall be of type int), it defines the postfix
10774 // increment operator ++ for objects of that type.
10775 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10776 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010777 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010778
Richard Smith538b52a2014-01-30 22:24:05 +000010779 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10780 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010781 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010782 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010783 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010784 }
10785
Douglas Gregord69246b2008-11-17 16:14:12 +000010786 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010787}
Chris Lattner3b024a32008-12-17 07:09:26 +000010788
Alexis Huntc88db062010-01-13 09:01:02 +000010789/// CheckLiteralOperatorDeclaration - Check whether the declaration
10790/// of this literal operator function is well-formed. If so, returns
10791/// false; otherwise, emits appropriate diagnostics and returns true.
10792bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010793 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010794 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10795 << FnDecl->getDeclName();
10796 return true;
10797 }
10798
Richard Smith72eebee2012-03-04 09:41:16 +000010799 if (FnDecl->isExternC()) {
10800 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10801 return true;
10802 }
10803
Alexis Huntc88db062010-01-13 09:01:02 +000010804 bool Valid = false;
10805
Richard Smithbcc22fc2012-03-09 08:00:36 +000010806 // This might be the definition of a literal operator template.
10807 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10808 // This might be a specialization of a literal operator template.
10809 if (!TpDecl)
10810 TpDecl = FnDecl->getPrimaryTemplate();
10811
Richard Smithb8b41d32013-10-07 19:57:58 +000010812 // template <char...> type operator "" name() and
10813 // template <class T, T...> type operator "" name() are the only valid
10814 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010815 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010816 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010817 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010818 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10819 if (Params->size() == 1) {
10820 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010821 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010822
Alexis Hunt7dd26172010-04-07 23:11:06 +000010823 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010824 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10825 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10826 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010827 } else if (Params->size() == 2) {
10828 TemplateTypeParmDecl *PmType =
10829 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10830 NonTypeTemplateParmDecl *PmArgs =
10831 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10832
10833 // The second template parameter must be a parameter pack with the
10834 // first template parameter as its type.
10835 if (PmType && PmArgs &&
10836 !PmType->isTemplateParameterPack() &&
10837 PmArgs->isTemplateParameterPack()) {
10838 const TemplateTypeParmType *TArgs =
10839 PmArgs->getType()->getAs<TemplateTypeParmType>();
10840 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10841 TArgs->getIndex() == PmType->getIndex()) {
10842 Valid = true;
10843 if (ActiveTemplateInstantiations.empty())
10844 Diag(FnDecl->getLocation(),
10845 diag::ext_string_literal_operator_template);
10846 }
10847 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010848 }
10849 }
Richard Smith72eebee2012-03-04 09:41:16 +000010850 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010851 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010852 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10853
Richard Smith72eebee2012-03-04 09:41:16 +000010854 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010855
Alexis Hunt079a6f72010-04-07 22:57:35 +000010856 // unsigned long long int, long double, and any character type are allowed
10857 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010858 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10859 Context.hasSameType(T, Context.LongDoubleTy) ||
10860 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010861 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010862 Context.hasSameType(T, Context.Char16Ty) ||
10863 Context.hasSameType(T, Context.Char32Ty)) {
10864 if (++Param == FnDecl->param_end())
10865 Valid = true;
10866 goto FinishedParams;
10867 }
10868
Alexis Hunt079a6f72010-04-07 22:57:35 +000010869 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010870 const PointerType *PT = T->getAs<PointerType>();
10871 if (!PT)
10872 goto FinishedParams;
10873 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010874 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010875 goto FinishedParams;
10876 T = T.getUnqualifiedType();
10877
10878 // Move on to the second parameter;
10879 ++Param;
10880
10881 // If there is no second parameter, the first must be a const char *
10882 if (Param == FnDecl->param_end()) {
10883 if (Context.hasSameType(T, Context.CharTy))
10884 Valid = true;
10885 goto FinishedParams;
10886 }
10887
10888 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10889 // are allowed as the first parameter to a two-parameter function
10890 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010891 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010892 Context.hasSameType(T, Context.Char16Ty) ||
10893 Context.hasSameType(T, Context.Char32Ty)))
10894 goto FinishedParams;
10895
10896 // The second and final parameter must be an std::size_t
10897 T = (*Param)->getType().getUnqualifiedType();
10898 if (Context.hasSameType(T, Context.getSizeType()) &&
10899 ++Param == FnDecl->param_end())
10900 Valid = true;
10901 }
10902
10903 // FIXME: This diagnostic is absolutely terrible.
10904FinishedParams:
10905 if (!Valid) {
10906 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10907 << FnDecl->getDeclName();
10908 return true;
10909 }
10910
Richard Smith768cecc2012-03-09 08:16:22 +000010911 // A parameter-declaration-clause containing a default argument is not
10912 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010913 for (auto Param : FnDecl->params()) {
10914 if (Param->hasDefaultArg()) {
10915 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000010916 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010917 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000010918 break;
10919 }
10920 }
10921
Richard Smith0df56f42012-03-08 02:39:21 +000010922 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010923 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10924 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010925 // C++11 [usrlit.suffix]p1:
10926 // Literal suffix identifiers that do not start with an underscore
10927 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010928 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10929 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010930 }
Richard Smith0df56f42012-03-08 02:39:21 +000010931
Alexis Huntc88db062010-01-13 09:01:02 +000010932 return false;
10933}
10934
Douglas Gregor07665a62009-01-05 19:45:36 +000010935/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10936/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000010937/// the '{'. ExternLoc is the location of the 'extern', Lang is the
10938/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000010939/// the '{' brace. Otherwise, this linkage specification does not
10940/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010941Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000010942 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000010943 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010944 StringLiteral *Lit = cast<StringLiteral>(LangStr);
10945 if (!Lit->isAscii()) {
10946 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
10947 << LangStr->getSourceRange();
10948 return 0;
10949 }
10950
10951 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000010952 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000010953 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000010954 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000010955 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000010956 Language = LinkageSpecDecl::lang_cxx;
10957 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000010958 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
10959 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010960 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000010961 }
Mike Stump11289f42009-09-09 15:08:12 +000010962
Chris Lattner438e5012008-12-17 07:13:27 +000010963 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000010964
Richard Smith4ee696d2014-02-17 23:25:27 +000010965 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
10966 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000010967 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000010968 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000010969 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000010970 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000010971}
10972
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000010973/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000010974/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10975/// valid, it's the position of the closing '}' brace in a linkage
10976/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000010977Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010978 Decl *LinkageSpec,
10979 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000010980 if (RBraceLoc.isValid()) {
10981 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10982 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000010983 }
Richard Smith4ee696d2014-02-17 23:25:27 +000010984 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000010985 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000010986}
10987
Michael Han84324352013-02-22 17:15:32 +000010988Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10989 AttributeList *AttrList,
10990 SourceLocation SemiLoc) {
10991 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10992 // Attribute declarations appertain to empty declaration so we handle
10993 // them here.
10994 if (AttrList)
10995 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000010996
Michael Han84324352013-02-22 17:15:32 +000010997 CurContext->addDecl(ED);
10998 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000010999}
11000
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011001/// \brief Perform semantic analysis for the variable declaration that
11002/// occurs within a C++ catch clause, returning the newly-created
11003/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011004VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011005 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011006 SourceLocation StartLoc,
11007 SourceLocation Loc,
11008 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011009 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011010 QualType ExDeclType = TInfo->getType();
11011
Sebastian Redl54c04d42008-12-22 19:15:10 +000011012 // Arrays and functions decay.
11013 if (ExDeclType->isArrayType())
11014 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11015 else if (ExDeclType->isFunctionType())
11016 ExDeclType = Context.getPointerType(ExDeclType);
11017
11018 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11019 // The exception-declaration shall not denote a pointer or reference to an
11020 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011021 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011022 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011023 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011024 Invalid = true;
11025 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011026
Sebastian Redl54c04d42008-12-22 19:15:10 +000011027 QualType BaseType = ExDeclType;
11028 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011029 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011030 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011031 BaseType = Ptr->getPointeeType();
11032 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011033 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011034 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011035 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011036 BaseType = Ref->getPointeeType();
11037 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011038 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011039 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011040 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011041 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011042 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011043
Mike Stump11289f42009-09-09 15:08:12 +000011044 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011045 RequireNonAbstractType(Loc, ExDeclType,
11046 diag::err_abstract_type_in_decl,
11047 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011048 Invalid = true;
11049
John McCall2ca705e2010-07-24 00:37:23 +000011050 // Only the non-fragile NeXT runtime currently supports C++ catches
11051 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011052 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011053 QualType T = ExDeclType;
11054 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11055 T = RT->getPointeeType();
11056
11057 if (T->isObjCObjectType()) {
11058 Diag(Loc, diag::err_objc_object_catch);
11059 Invalid = true;
11060 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011061 // FIXME: should this be a test for macosx-fragile specifically?
11062 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011063 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011064 }
11065 }
11066
Abramo Bagnaradff19302011-03-08 08:55:46 +000011067 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011068 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011069 ExDecl->setExceptionVariable(true);
11070
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011071 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011072 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011073 Invalid = true;
11074
Douglas Gregor750734c2011-07-06 18:14:43 +000011075 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011076 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011077 // Insulate this from anything else we might currently be parsing.
11078 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11079
Douglas Gregor6de584c2010-03-05 23:38:39 +000011080 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011081 // The object declared in an exception-declaration or, if the
11082 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011083 // copy-initialized (8.5) from the exception object. [...]
11084 // The object is destroyed when the handler exits, after the destruction
11085 // of any automatic objects initialized within the handler.
11086 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011087 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011088 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011089 QualType initType = ExDeclType;
11090
11091 InitializedEntity entity =
11092 InitializedEntity::InitializeVariable(ExDecl);
11093 InitializationKind initKind =
11094 InitializationKind::CreateCopy(Loc, SourceLocation());
11095
11096 Expr *opaqueValue =
11097 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011098 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11099 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011100 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011101 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011102 else {
11103 // If the constructor used was non-trivial, set this as the
11104 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011105 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011106 if (!construct->getConstructor()->isTrivial()) {
11107 Expr *init = MaybeCreateExprWithCleanups(construct);
11108 ExDecl->setInit(init);
11109 }
11110
11111 // And make sure it's destructable.
11112 FinalizeVarWithDestructor(ExDecl, recordType);
11113 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011114 }
11115 }
11116
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011117 if (Invalid)
11118 ExDecl->setInvalidDecl();
11119
11120 return ExDecl;
11121}
11122
11123/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11124/// handler.
John McCall48871652010-08-21 09:40:31 +000011125Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011126 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011127 bool Invalid = D.isInvalidType();
11128
11129 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011130 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11131 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011132 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11133 D.getIdentifierLoc());
11134 Invalid = true;
11135 }
11136
Sebastian Redl54c04d42008-12-22 19:15:10 +000011137 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011138 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011139 LookupOrdinaryName,
11140 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011141 // The scope should be freshly made just for us. There is just no way
11142 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011143 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011144 if (PrevDecl->isTemplateParameter()) {
11145 // Maybe we will complain about the shadowed template parameter.
11146 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011147 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011148 }
11149 }
11150
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011151 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011152 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11153 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011154 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011155 }
11156
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011157 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011158 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011159 D.getIdentifierLoc(),
11160 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011161 if (Invalid)
11162 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011163
Sebastian Redl54c04d42008-12-22 19:15:10 +000011164 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011165 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011166 PushOnScopeChains(ExDecl, S);
11167 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011168 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011169
Douglas Gregor758a8692009-06-17 21:51:59 +000011170 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011171 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011172}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011173
Abramo Bagnaraea947882011-03-08 16:41:52 +000011174Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011175 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011176 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011177 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011178 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011179
Richard Smithded9c2e2012-07-11 22:37:56 +000011180 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11181 return 0;
11182
11183 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11184 AssertMessage, RParenLoc, false);
11185}
11186
11187Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11188 Expr *AssertExpr,
11189 StringLiteral *AssertMessage,
11190 SourceLocation RParenLoc,
11191 bool Failed) {
11192 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11193 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011194 // In a static_assert-declaration, the constant-expression shall be a
11195 // constant expression that can be contextually converted to bool.
11196 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11197 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011198 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011199
Richard Smith902ca212011-12-14 23:32:26 +000011200 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011201 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011202 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011203 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011204 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011205
Richard Smithded9c2e2012-07-11 22:37:56 +000011206 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011207 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011208 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011209 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011210 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011211 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011212 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011213 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011214 }
Mike Stump11289f42009-09-09 15:08:12 +000011215
Abramo Bagnaraea947882011-03-08 16:41:52 +000011216 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011217 AssertExpr, AssertMessage, RParenLoc,
11218 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011219
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011220 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011221 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011222}
Sebastian Redlf769df52009-03-24 22:27:57 +000011223
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011224/// \brief Perform semantic analysis of the given friend type declaration.
11225///
11226/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011227FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011228 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011229 TypeSourceInfo *TSInfo) {
11230 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11231
11232 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011233 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011234
Richard Smithc8239732011-10-18 21:39:00 +000011235 // C++03 [class.friend]p2:
11236 // An elaborated-type-specifier shall be used in a friend declaration
11237 // for a class.*
11238 //
11239 // * The class-key of the elaborated-type-specifier is required.
11240 if (!ActiveTemplateInstantiations.empty()) {
11241 // Do not complain about the form of friend template types during
11242 // template instantiation; we will already have complained when the
11243 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011244 } else {
11245 if (!T->isElaboratedTypeSpecifier()) {
11246 // If we evaluated the type to a record type, suggest putting
11247 // a tag in front.
11248 if (const RecordType *RT = T->getAs<RecordType>()) {
11249 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011250
Nick Lewycky36722d22013-02-06 05:59:33 +000011251 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011252
Nick Lewycky36722d22013-02-06 05:59:33 +000011253 Diag(TypeRange.getBegin(),
11254 getLangOpts().CPlusPlus11 ?
11255 diag::warn_cxx98_compat_unelaborated_friend_type :
11256 diag::ext_unelaborated_friend_type)
11257 << (unsigned) RD->getTagKind()
11258 << T
11259 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11260 InsertionText);
11261 } else {
11262 Diag(FriendLoc,
11263 getLangOpts().CPlusPlus11 ?
11264 diag::warn_cxx98_compat_nonclass_type_friend :
11265 diag::ext_nonclass_type_friend)
11266 << T
11267 << TypeRange;
11268 }
11269 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011270 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011271 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011272 diag::warn_cxx98_compat_enum_friend :
11273 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011274 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011275 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011276 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011277
Nick Lewycky36722d22013-02-06 05:59:33 +000011278 // C++11 [class.friend]p3:
11279 // A friend declaration that does not declare a function shall have one
11280 // of the following forms:
11281 // friend elaborated-type-specifier ;
11282 // friend simple-type-specifier ;
11283 // friend typename-specifier ;
11284 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11285 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11286 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011287
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011288 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011289 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011290 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011291 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011292}
11293
John McCallace48cd2010-10-19 01:40:49 +000011294/// Handle a friend tag declaration where the scope specifier was
11295/// templated.
11296Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11297 unsigned TagSpec, SourceLocation TagLoc,
11298 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011299 IdentifierInfo *Name,
11300 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011301 AttributeList *Attr,
11302 MultiTemplateParamsArg TempParamLists) {
11303 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11304
11305 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011306 bool Invalid = false;
11307
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011308 if (TemplateParameterList *TemplateParams =
11309 MatchTemplateParametersToScopeSpecifier(
11310 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11311 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011312 if (TemplateParams->size() > 0) {
11313 // This is a declaration of a class template.
11314 if (Invalid)
11315 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011316
Eric Christopher6f228b52011-07-21 05:34:24 +000011317 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11318 SS, Name, NameLoc, Attr,
11319 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011320 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011321 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011322 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011323 } else {
11324 // The "template<>" header is extraneous.
11325 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11326 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11327 isExplicitSpecialization = true;
11328 }
11329 }
11330
11331 if (Invalid) return 0;
11332
John McCallace48cd2010-10-19 01:40:49 +000011333 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011334 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011335 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011336 isAllExplicitSpecializations = false;
11337 break;
11338 }
11339 }
11340
11341 // FIXME: don't ignore attributes.
11342
11343 // If it's explicit specializations all the way down, just forget
11344 // about the template header and build an appropriate non-templated
11345 // friend. TODO: for source fidelity, remember the headers.
11346 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011347 if (SS.isEmpty()) {
11348 bool Owned = false;
11349 bool IsDependent = false;
11350 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011351 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011352 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011353 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011354 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011355 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011356 /*UnderlyingType=*/TypeResult(),
11357 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011358 }
Richard Smith649c7b062014-01-08 00:56:48 +000011359
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011360 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011361 ElaboratedTypeKeyword Keyword
11362 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011363 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011364 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011365 if (T.isNull())
11366 return 0;
11367
11368 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11369 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011370 DependentNameTypeLoc TL =
11371 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011372 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011373 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011374 TL.setNameLoc(NameLoc);
11375 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011376 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011377 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011378 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011379 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011380 }
11381
11382 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011383 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011384 Friend->setAccess(AS_public);
11385 CurContext->addDecl(Friend);
11386 return Friend;
11387 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011388
11389 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11390
11391
John McCallace48cd2010-10-19 01:40:49 +000011392
11393 // Handle the case of a templated-scope friend class. e.g.
11394 // template <class T> class A<T>::B;
11395 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011396 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11397 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011398 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11399 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11400 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011401 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011402 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011403 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011404 TL.setNameLoc(NameLoc);
11405
11406 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011407 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011408 Friend->setAccess(AS_public);
11409 Friend->setUnsupportedFriend(true);
11410 CurContext->addDecl(Friend);
11411 return Friend;
11412}
11413
11414
John McCall11083da2009-09-16 22:47:08 +000011415/// Handle a friend type declaration. This works in tandem with
11416/// ActOnTag.
11417///
11418/// Notes on friend class templates:
11419///
11420/// We generally treat friend class declarations as if they were
11421/// declaring a class. So, for example, the elaborated type specifier
11422/// in a friend declaration is required to obey the restrictions of a
11423/// class-head (i.e. no typedefs in the scope chain), template
11424/// parameters are required to match up with simple template-ids, &c.
11425/// However, unlike when declaring a template specialization, it's
11426/// okay to refer to a template specialization without an empty
11427/// template parameter declaration, e.g.
11428/// friend class A<T>::B<unsigned>;
11429/// We permit this as a special case; if there are any template
11430/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011431/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011432Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011433 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011434 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011435
11436 assert(DS.isFriendSpecified());
11437 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11438
John McCall11083da2009-09-16 22:47:08 +000011439 // Try to convert the decl specifier to a type. This works for
11440 // friend templates because ActOnTag never produces a ClassTemplateDecl
11441 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011442 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011443 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11444 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011445 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011446 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011447
Douglas Gregor6c110f32010-12-16 01:14:37 +000011448 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11449 return 0;
11450
John McCall11083da2009-09-16 22:47:08 +000011451 // This is definitely an error in C++98. It's probably meant to
11452 // be forbidden in C++0x, too, but the specification is just
11453 // poorly written.
11454 //
11455 // The problem is with declarations like the following:
11456 // template <T> friend A<T>::foo;
11457 // where deciding whether a class C is a friend or not now hinges
11458 // on whether there exists an instantiation of A that causes
11459 // 'foo' to equal C. There are restrictions on class-heads
11460 // (which we declare (by fiat) elaborated friend declarations to
11461 // be) that makes this tractable.
11462 //
11463 // FIXME: handle "template <> friend class A<T>;", which
11464 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011465 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011466 Diag(Loc, diag::err_tagless_friend_type_template)
11467 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011468 return 0;
John McCall11083da2009-09-16 22:47:08 +000011469 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011470
John McCallaa74a0c2009-08-28 07:59:38 +000011471 // C++98 [class.friend]p1: A friend of a class is a function
11472 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011473 // This is fixed in DR77, which just barely didn't make the C++03
11474 // deadline. It's also a very silly restriction that seriously
11475 // affects inner classes and which nobody else seems to implement;
11476 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011477 //
11478 // But note that we could warn about it: it's always useless to
11479 // friend one of your own members (it's not, however, worthless to
11480 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011481
John McCall11083da2009-09-16 22:47:08 +000011482 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011483 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011484 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011485 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011486 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011487 TSI,
John McCall11083da2009-09-16 22:47:08 +000011488 DS.getFriendSpecLoc());
11489 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011490 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011491
11492 if (!D)
John McCall48871652010-08-21 09:40:31 +000011493 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011494
John McCall11083da2009-09-16 22:47:08 +000011495 D->setAccess(AS_public);
11496 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011497
John McCall48871652010-08-21 09:40:31 +000011498 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011499}
11500
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011501NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11502 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011503 const DeclSpec &DS = D.getDeclSpec();
11504
11505 assert(DS.isFriendSpecified());
11506 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11507
11508 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011509 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011510
11511 // C++ [class.friend]p1
11512 // A friend of a class is a function or class....
11513 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011514 // It *doesn't* see through dependent types, which is correct
11515 // according to [temp.arg.type]p3:
11516 // If a declaration acquires a function type through a
11517 // type dependent on a template-parameter and this causes
11518 // a declaration that does not use the syntactic form of a
11519 // function declarator to have a function type, the program
11520 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011521 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011522 Diag(Loc, diag::err_unexpected_friend);
11523
11524 // It might be worthwhile to try to recover by creating an
11525 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011526 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011527 }
11528
11529 // C++ [namespace.memdef]p3
11530 // - If a friend declaration in a non-local class first declares a
11531 // class or function, the friend class or function is a member
11532 // of the innermost enclosing namespace.
11533 // - The name of the friend is not found by simple name lookup
11534 // until a matching declaration is provided in that namespace
11535 // scope (either before or after the class declaration granting
11536 // friendship).
11537 // - If a friend function is called, its name may be found by the
11538 // name lookup that considers functions from namespaces and
11539 // classes associated with the types of the function arguments.
11540 // - When looking for a prior declaration of a class or a function
11541 // declared as a friend, scopes outside the innermost enclosing
11542 // namespace scope are not considered.
11543
John McCallde3fd222010-10-12 23:13:28 +000011544 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011545 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11546 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011547 assert(Name);
11548
Douglas Gregor6c110f32010-12-16 01:14:37 +000011549 // Check for unexpanded parameter packs.
11550 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11551 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11552 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11553 return 0;
11554
John McCall07e91c02009-08-06 02:15:43 +000011555 // The context we found the declaration in, or in which we should
11556 // create the declaration.
11557 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011558 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011559 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011560 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011561
Richard Smith114394f2013-08-09 04:35:01 +000011562 // There are five cases here.
11563 // - There's no scope specifier and we're in a local class. Only look
11564 // for functions declared in the immediately-enclosing block scope.
11565 // We recover from invalid scope qualifiers as if they just weren't there.
11566 FunctionDecl *FunctionContainingLocalClass = 0;
11567 if ((SS.isInvalid() || !SS.isSet()) &&
11568 (FunctionContainingLocalClass =
11569 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11570 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011571 // If a friend declaration appears in a local class and the name
11572 // specified is an unqualified name, a prior declaration is
11573 // looked up without considering scopes that are outside the
11574 // innermost enclosing non-class scope. For a friend function
11575 // declaration, if there is no prior declaration, the program is
11576 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011577
11578 // Find the innermost enclosing non-class scope. This is the block
11579 // scope containing the local class definition (or for a nested class,
11580 // the outer local class).
11581 DCScope = S->getFnParent();
11582
11583 // Look up the function name in the scope.
11584 Previous.clear(LookupLocalFriendName);
11585 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11586
11587 if (!Previous.empty()) {
11588 // All possible previous declarations must have the same context:
11589 // either they were declared at block scope or they are members of
11590 // one of the enclosing local classes.
11591 DC = Previous.getRepresentativeDecl()->getDeclContext();
11592 } else {
11593 // This is ill-formed, but provide the context that we would have
11594 // declared the function in, if we were permitted to, for error recovery.
11595 DC = FunctionContainingLocalClass;
11596 }
Richard Smith541b38b2013-09-20 01:15:31 +000011597 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011598
11599 // C++ [class.friend]p6:
11600 // A function can be defined in a friend declaration of a class if and
11601 // only if the class is a non-local class (9.8), the function name is
11602 // unqualified, and the function has namespace scope.
11603 if (D.isFunctionDefinition()) {
11604 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11605 }
11606
11607 // - There's no scope specifier, in which case we just go to the
11608 // appropriate scope and look for a function or function template
11609 // there as appropriate.
11610 } else if (SS.isInvalid() || !SS.isSet()) {
11611 // C++11 [namespace.memdef]p3:
11612 // If the name in a friend declaration is neither qualified nor
11613 // a template-id and the declaration is a function or an
11614 // elaborated-type-specifier, the lookup to determine whether
11615 // the entity has been previously declared shall not consider
11616 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011617 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011618
John McCallf7cfb222010-10-13 05:45:15 +000011619 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011620 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011621
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011622 // Skip class contexts. If someone can cite chapter and verse
11623 // for this behavior, that would be nice --- it's what GCC and
11624 // EDG do, and it seems like a reasonable intent, but the spec
11625 // really only says that checks for unqualified existing
11626 // declarations should stop at the nearest enclosing namespace,
11627 // not that they should only consider the nearest enclosing
11628 // namespace.
11629 while (DC->isRecord())
11630 DC = DC->getParent();
11631
11632 DeclContext *LookupDC = DC;
11633 while (LookupDC->isTransparentContext())
11634 LookupDC = LookupDC->getParent();
11635
11636 while (true) {
11637 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011638
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011639 if (!Previous.empty()) {
11640 DC = LookupDC;
11641 break;
John McCallf4776592010-10-14 22:22:28 +000011642 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011643
11644 if (isTemplateId) {
11645 if (isa<TranslationUnitDecl>(LookupDC)) break;
11646 } else {
11647 if (LookupDC->isFileContext()) break;
11648 }
11649 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011650 }
11651
John McCallccbc0322010-10-13 06:22:15 +000011652 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011653
John McCallde3fd222010-10-12 23:13:28 +000011654 // - There's a non-dependent scope specifier, in which case we
11655 // compute it and do a previous lookup there for a function
11656 // or function template.
11657 } else if (!SS.getScopeRep()->isDependent()) {
11658 DC = computeDeclContext(SS);
11659 if (!DC) return 0;
11660
11661 if (RequireCompleteDeclContext(SS, DC)) return 0;
11662
11663 LookupQualifiedName(Previous, DC);
11664
11665 // Ignore things found implicitly in the wrong scope.
11666 // TODO: better diagnostics for this case. Suggesting the right
11667 // qualified scope would be nice...
11668 LookupResult::Filter F = Previous.makeFilter();
11669 while (F.hasNext()) {
11670 NamedDecl *D = F.next();
11671 if (!DC->InEnclosingNamespaceSetOf(
11672 D->getDeclContext()->getRedeclContext()))
11673 F.erase();
11674 }
11675 F.done();
11676
11677 if (Previous.empty()) {
11678 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011679 Diag(Loc, diag::err_qualified_friend_not_found)
11680 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011681 return 0;
11682 }
11683
11684 // C++ [class.friend]p1: A friend of a class is a function or
11685 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011686 if (DC->Equals(CurContext))
11687 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011688 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011689 diag::warn_cxx98_compat_friend_is_member :
11690 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011691
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011692 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011693 // C++ [class.friend]p6:
11694 // A function can be defined in a friend declaration of a class if and
11695 // only if the class is a non-local class (9.8), the function name is
11696 // unqualified, and the function has namespace scope.
11697 SemaDiagnosticBuilder DB
11698 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11699
11700 DB << SS.getScopeRep();
11701 if (DC->isFileContext())
11702 DB << FixItHint::CreateRemoval(SS.getRange());
11703 SS.clear();
11704 }
John McCallde3fd222010-10-12 23:13:28 +000011705
11706 // - There's a scope specifier that does not match any template
11707 // parameter lists, in which case we use some arbitrary context,
11708 // create a method or method template, and wait for instantiation.
11709 // - There's a scope specifier that does match some template
11710 // parameter lists, which we don't handle right now.
11711 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011712 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011713 // C++ [class.friend]p6:
11714 // A function can be defined in a friend declaration of a class if and
11715 // only if the class is a non-local class (9.8), the function name is
11716 // unqualified, and the function has namespace scope.
11717 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11718 << SS.getScopeRep();
11719 }
11720
John McCallde3fd222010-10-12 23:13:28 +000011721 DC = CurContext;
11722 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011723 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011724
John McCallf7cfb222010-10-13 05:45:15 +000011725 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011726 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011727 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11728 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11729 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011730 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011731 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11732 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011733 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011734 }
John McCall07e91c02009-08-06 02:15:43 +000011735 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011736
Douglas Gregordd847ba2011-11-03 16:37:14 +000011737 // FIXME: This is an egregious hack to cope with cases where the scope stack
11738 // does not contain the declaration context, i.e., in an out-of-line
11739 // definition of a class.
11740 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11741 if (!DCScope) {
11742 FakeDCScope.setEntity(DC);
11743 DCScope = &FakeDCScope;
11744 }
Richard Smith114394f2013-08-09 04:35:01 +000011745
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011746 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011747 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011748 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011749 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011750
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011751 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011752
Richard Smith114394f2013-08-09 04:35:01 +000011753 // If we performed typo correction, we might have added a scope specifier
11754 // and changed the decl context.
11755 DC = ND->getDeclContext();
11756
John McCall759e32b2009-08-31 22:39:49 +000011757 // Add the function declaration to the appropriate lookup tables,
11758 // adjusting the redeclarations list as necessary. We don't
11759 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011760 //
John McCall759e32b2009-08-31 22:39:49 +000011761 // Also update the scope-based lookup if the target context's
11762 // lookup context is in lexical scope.
11763 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011764 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011765 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011766 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011767 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011768 }
John McCallaa74a0c2009-08-28 07:59:38 +000011769
11770 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011771 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011772 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011773 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011774 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011775
John McCalla0a96892012-08-10 03:15:35 +000011776 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011777 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011778 } else {
11779 if (DC->isRecord()) CheckFriendAccess(ND);
11780
John McCall2c2eb122010-10-16 06:59:13 +000011781 FunctionDecl *FD;
11782 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11783 FD = FTD->getTemplatedDecl();
11784 else
11785 FD = cast<FunctionDecl>(ND);
11786
David Majnemer502b0ed2013-06-25 23:09:30 +000011787 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11788 // default argument expression, that declaration shall be a definition
11789 // and shall be the only declaration of the function or function
11790 // template in the translation unit.
11791 if (functionDeclHasDefaultArgument(FD)) {
11792 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11793 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11794 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11795 } else if (!D.isFunctionDefinition())
11796 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11797 }
11798
John McCall2c2eb122010-10-16 06:59:13 +000011799 // Mark templated-scope function declarations as unsupported.
11800 if (FD->getNumTemplateParameterLists())
11801 FrD->setUnsupportedFriend(true);
11802 }
John McCallde3fd222010-10-12 23:13:28 +000011803
John McCall48871652010-08-21 09:40:31 +000011804 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011805}
11806
John McCall48871652010-08-21 09:40:31 +000011807void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11808 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011809
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011810 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011811 if (!Fn) {
11812 Diag(DelLoc, diag::err_deleted_non_function);
11813 return;
11814 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011815
Douglas Gregorec9fd132012-01-14 16:38:05 +000011816 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011817 // Don't consider the implicit declaration we generate for explicit
11818 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011819 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11820 Prev->getPreviousDecl()) &&
11821 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011822 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011823 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11824 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11825 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011826 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011827 // If the declaration wasn't the first, we delete the function anyway for
11828 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011829 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011830 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011831
11832 if (Fn->isDeleted())
11833 return;
11834
11835 // See if we're deleting a function which is already known to override a
11836 // non-deleted virtual function.
11837 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11838 bool IssuedDiagnostic = false;
11839 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11840 E = MD->end_overridden_methods();
11841 I != E; ++I) {
11842 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11843 if (!IssuedDiagnostic) {
11844 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11845 IssuedDiagnostic = true;
11846 }
11847 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11848 }
11849 }
11850 }
11851
Richard Smithb63b6ee2014-01-22 01:43:19 +000011852 // C++11 [basic.start.main]p3:
11853 // A program that defines main as deleted [...] is ill-formed.
11854 if (Fn->isMain())
11855 Diag(DelLoc, diag::err_deleted_main);
11856
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011857 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011858}
Sebastian Redl4c018662009-04-27 21:33:24 +000011859
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011860void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011861 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011862
11863 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011864 if (MD->getParent()->isDependentType()) {
11865 MD->setDefaulted();
11866 MD->setExplicitlyDefaulted();
11867 return;
11868 }
11869
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011870 CXXSpecialMember Member = getSpecialMember(MD);
11871 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011872 if (!MD->isInvalidDecl())
11873 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011874 return;
11875 }
11876
11877 MD->setDefaulted();
11878 MD->setExplicitlyDefaulted();
11879
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011880 // If this definition appears within the record, do the checking when
11881 // the record is complete.
11882 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011883 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011884 // Find the uninstantiated declaration that actually had the '= default'
11885 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011886 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011887
Richard Smith3901dfe2013-03-27 00:22:47 +000011888 // If the method was defaulted on its first declaration, we will have
11889 // already performed the checking in CheckCompletedCXXClass. Such a
11890 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011891 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011892 return;
11893
Richard Smithd3b5c9082012-07-27 04:22:15 +000011894 CheckExplicitlyDefaultedSpecialMember(MD);
11895
Richard Smithbd305122012-12-11 01:14:52 +000011896 // The exception specification is needed because we are defining the
11897 // function.
11898 ResolveExceptionSpec(DefaultLoc,
11899 MD->getType()->castAs<FunctionProtoType>());
11900
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011901 if (MD->isInvalidDecl())
11902 return;
11903
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011904 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011905 case CXXDefaultConstructor:
11906 DefineImplicitDefaultConstructor(DefaultLoc,
11907 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011908 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011909 case CXXCopyConstructor:
11910 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011911 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011912 case CXXCopyAssignment:
11913 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011914 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011915 case CXXDestructor:
11916 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011917 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011918 case CXXMoveConstructor:
11919 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011920 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011921 case CXXMoveAssignment:
11922 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011923 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011924 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011925 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011926 }
11927 } else {
11928 Diag(DefaultLoc, diag::err_default_special_members);
11929 }
11930}
11931
Sebastian Redl4c018662009-04-27 21:33:24 +000011932static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011933 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011934 Stmt *SubStmt = *CI;
11935 if (!SubStmt)
11936 continue;
11937 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011938 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011939 diag::err_return_in_constructor_handler);
11940 if (!isa<Expr>(SubStmt))
11941 SearchForReturnInStmt(Self, SubStmt);
11942 }
11943}
11944
11945void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11946 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11947 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11948 SearchForReturnInStmt(*this, Handler);
11949 }
11950}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011951
David Blaikie68f71a32013-01-18 23:03:15 +000011952bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000011953 const CXXMethodDecl *Old) {
11954 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11955 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11956
11957 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11958
11959 // If the calling conventions match, everything is fine
11960 if (NewCC == OldCC)
11961 return false;
11962
Hans Wennborg2545efe2013-12-11 17:42:11 +000011963 // If the calling conventions mismatch because the new function is static,
11964 // suppress the calling convention mismatch error; the error about static
11965 // function override (err_static_overrides_virtual from
11966 // Sema::CheckFunctionDeclaration) is more clear.
11967 if (New->getStorageClass() == SC_Static)
11968 return false;
11969
Reid Kleckner78af0702013-08-27 23:08:25 +000011970 Diag(New->getLocation(),
11971 diag::err_conflicting_overriding_cc_attributes)
11972 << New->getDeclName() << New->getType() << Old->getType();
11973 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11974 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000011975}
11976
Mike Stump11289f42009-09-09 15:08:12 +000011977bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011978 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000011979 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
11980 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011981
Chandler Carruth284bb2e2010-02-15 11:53:20 +000011982 if (Context.hasSameType(NewTy, OldTy) ||
11983 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011984 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011985
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011986 // Check if the return types are covariant
11987 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000011988
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011989 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011990 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11991 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000011992 NewClassTy = NewPT->getPointeeType();
11993 OldClassTy = OldPT->getPointeeType();
11994 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000011995 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11996 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11997 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11998 NewClassTy = NewRT->getPointeeType();
11999 OldClassTy = OldRT->getPointeeType();
12000 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012001 }
12002 }
Mike Stump11289f42009-09-09 15:08:12 +000012003
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012004 // The return types aren't either both pointers or references to a class type.
12005 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012006 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012007 diag::err_different_return_type_for_overriding_virtual_function)
12008 << New->getDeclName() << NewTy << OldTy;
12009 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012010
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012011 return true;
12012 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012013
Anders Carlssone60365b2009-12-31 18:34:24 +000012014 // C++ [class.virtual]p6:
12015 // If the return type of D::f differs from the return type of B::f, the
12016 // class type in the return type of D::f shall be complete at the point of
12017 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012018 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12019 if (!RT->isBeingDefined() &&
12020 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012021 diag::err_covariant_return_incomplete,
12022 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012023 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012024 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012025
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012026 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012027 // Check if the new class derives from the old class.
12028 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12029 Diag(New->getLocation(),
12030 diag::err_covariant_return_not_derived)
12031 << New->getDeclName() << NewTy << OldTy;
12032 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12033 return true;
12034 }
Mike Stump11289f42009-09-09 15:08:12 +000012035
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012036 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012037 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012038 diag::err_covariant_return_inaccessible_base,
12039 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12040 // FIXME: Should this point to the return type?
12041 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012042 // FIXME: this note won't trigger for delayed access control
12043 // diagnostics, and it's impossible to get an undelayed error
12044 // here from access control during the original parse because
12045 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012046 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12047 return true;
12048 }
12049 }
Mike Stump11289f42009-09-09 15:08:12 +000012050
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012051 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012052 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012053 Diag(New->getLocation(),
12054 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012055 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012056 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12057 return true;
12058 };
Mike Stump11289f42009-09-09 15:08:12 +000012059
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012060
12061 // The new class type must have the same or less qualifiers as the old type.
12062 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12063 Diag(New->getLocation(),
12064 diag::err_covariant_return_type_class_type_more_qualified)
12065 << New->getDeclName() << NewTy << OldTy;
12066 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12067 return true;
12068 };
Mike Stump11289f42009-09-09 15:08:12 +000012069
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012070 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012071}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012072
Douglas Gregor21920e372009-12-01 17:24:26 +000012073/// \brief Mark the given method pure.
12074///
12075/// \param Method the method to be marked pure.
12076///
12077/// \param InitRange the source range that covers the "0" initializer.
12078bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012079 SourceLocation EndLoc = InitRange.getEnd();
12080 if (EndLoc.isValid())
12081 Method->setRangeEnd(EndLoc);
12082
Douglas Gregor21920e372009-12-01 17:24:26 +000012083 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12084 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012085 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012086 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012087
12088 if (!Method->isInvalidDecl())
12089 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12090 << Method->getDeclName() << InitRange;
12091 return true;
12092}
12093
Douglas Gregor926410d2012-02-21 02:22:07 +000012094/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012095static bool isStaticDataMember(const Decl *D) {
12096 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12097 return Var->isStaticDataMember();
12098
12099 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012100}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012101
John McCall1f4ee7b2009-12-19 09:28:58 +000012102/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12103/// an initializer for the out-of-line declaration 'Dcl'. The scope
12104/// is a fresh scope pushed for just this purpose.
12105///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012106/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12107/// static data member of class X, names should be looked up in the scope of
12108/// class X.
John McCall48871652010-08-21 09:40:31 +000012109void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012110 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012111 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012112
Richard Smitha2302242013-12-05 07:51:02 +000012113 // We will always have a nested name specifier here, but this declaration
12114 // might not be out of line if the specifier names the current namespace:
12115 // extern int n;
12116 // int ::n = 0;
12117 if (D->isOutOfLine())
12118 EnterDeclaratorContext(S, D->getDeclContext());
12119
Douglas Gregor926410d2012-02-21 02:22:07 +000012120 // If we are parsing the initializer for a static data member, push a
12121 // new expression evaluation context that is associated with this static
12122 // data member.
12123 if (isStaticDataMember(D))
12124 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012125}
12126
12127/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012128/// initializer for the out-of-line declaration 'D'.
12129void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012130 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012131 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012132
Douglas Gregor926410d2012-02-21 02:22:07 +000012133 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012134 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012135
Richard Smitha2302242013-12-05 07:51:02 +000012136 if (D->isOutOfLine())
12137 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012138}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012139
12140/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12141/// C++ if/switch/while/for statement.
12142/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012143DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012144 // C++ 6.4p2:
12145 // The declarator shall not specify a function or an array.
12146 // The type-specifier-seq shall not contain typedef and shall not declare a
12147 // new class or enumeration.
12148 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12149 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012150
12151 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012152 if (!Dcl)
12153 return true;
12154
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012155 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12156 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012157 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012158 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012159 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012160
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012161 return Dcl;
12162}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012163
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012164void Sema::LoadExternalVTableUses() {
12165 if (!ExternalSource)
12166 return;
12167
12168 SmallVector<ExternalVTableUse, 4> VTables;
12169 ExternalSource->ReadUsedVTables(VTables);
12170 SmallVector<VTableUse, 4> NewUses;
12171 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12172 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12173 = VTablesUsed.find(VTables[I].Record);
12174 // Even if a definition wasn't required before, it may be required now.
12175 if (Pos != VTablesUsed.end()) {
12176 if (!Pos->second && VTables[I].DefinitionRequired)
12177 Pos->second = true;
12178 continue;
12179 }
12180
12181 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12182 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12183 }
12184
12185 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12186}
12187
Douglas Gregor88d292c2010-05-13 16:44:06 +000012188void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12189 bool DefinitionRequired) {
12190 // Ignore any vtable uses in unevaluated operands or for classes that do
12191 // not have a vtable.
12192 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012193 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012194 return;
12195
Douglas Gregor88d292c2010-05-13 16:44:06 +000012196 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012197 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012198 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12199 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12200 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12201 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012202 // If we already had an entry, check to see if we are promoting this vtable
12203 // to required a definition. If so, we need to reappend to the VTableUses
12204 // list, since we may have already processed the first entry.
12205 if (DefinitionRequired && !Pos.first->second) {
12206 Pos.first->second = true;
12207 } else {
12208 // Otherwise, we can early exit.
12209 return;
12210 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012211 } else {
12212 // The Microsoft ABI requires that we perform the destructor body
12213 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12214 // the deleting destructor is emitted with the vtable, not with the
12215 // destructor definition as in the Itanium ABI.
12216 // If it has a definition, we do the check at that point instead.
12217 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12218 Class->hasUserDeclaredDestructor() &&
12219 !Class->getDestructor()->isDefined() &&
12220 !Class->getDestructor()->isDeleted()) {
12221 CheckDestructor(Class->getDestructor());
12222 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012223 }
12224
12225 // Local classes need to have their virtual members marked
12226 // immediately. For all other classes, we mark their virtual members
12227 // at the end of the translation unit.
12228 if (Class->isLocalClass())
12229 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012230 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012231 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012232}
12233
Douglas Gregor88d292c2010-05-13 16:44:06 +000012234bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012235 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012236 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012237 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012238
Douglas Gregor88d292c2010-05-13 16:44:06 +000012239 // Note: The VTableUses vector could grow as a result of marking
12240 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012241 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012242 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012243 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012244 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012245 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012246 if (!Class)
12247 continue;
12248
12249 SourceLocation Loc = VTableUses[I].second;
12250
Richard Smithd3b5c9082012-07-27 04:22:15 +000012251 bool DefineVTable = true;
12252
Douglas Gregor88d292c2010-05-13 16:44:06 +000012253 // If this class has a key function, but that key function is
12254 // defined in another translation unit, we don't need to emit the
12255 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012256 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012257 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012258 // The key function is in another translation unit.
12259 DefineVTable = false;
12260 TemplateSpecializationKind TSK =
12261 KeyFunction->getTemplateSpecializationKind();
12262 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12263 TSK != TSK_ImplicitInstantiation &&
12264 "Instantiations don't have key functions");
12265 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012266 } else if (!KeyFunction) {
12267 // If we have a class with no key function that is the subject
12268 // of an explicit instantiation declaration, suppress the
12269 // vtable; it will live with the explicit instantiation
12270 // definition.
12271 bool IsExplicitInstantiationDeclaration
12272 = Class->getTemplateSpecializationKind()
12273 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012274 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012275 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012276 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012277 if (TSK == TSK_ExplicitInstantiationDeclaration)
12278 IsExplicitInstantiationDeclaration = true;
12279 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12280 IsExplicitInstantiationDeclaration = false;
12281 break;
12282 }
12283 }
12284
12285 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012286 DefineVTable = false;
12287 }
12288
12289 // The exception specifications for all virtual members may be needed even
12290 // if we are not providing an authoritative form of the vtable in this TU.
12291 // We may choose to emit it available_externally anyway.
12292 if (!DefineVTable) {
12293 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12294 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012295 }
12296
12297 // Mark all of the virtual members of this class as referenced, so
12298 // that we can build a vtable. Then, tell the AST consumer that a
12299 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012300 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012301 MarkVirtualMembersReferenced(Loc, Class);
12302 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12303 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12304
12305 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012306 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012307 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012308 const FunctionDecl *KeyFunctionDef = 0;
12309 if (!KeyFunction ||
12310 (KeyFunction->hasBody(KeyFunctionDef) &&
12311 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012312 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12313 TSK_ExplicitInstantiationDefinition
12314 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12315 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012316 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012317 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012318 VTableUses.clear();
12319
Douglas Gregor97509692011-04-22 22:25:37 +000012320 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012321}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012322
Richard Smithd3b5c9082012-07-27 04:22:15 +000012323void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12324 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012325 for (const auto *I : RD->methods())
12326 if (I->isVirtual() && !I->isPure())
12327 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012328}
12329
Rafael Espindola5b334082010-03-26 00:36:59 +000012330void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12331 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012332 // Mark all functions which will appear in RD's vtable as used.
12333 CXXFinalOverriderMap FinalOverriders;
12334 RD->getFinalOverriders(FinalOverriders);
12335 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12336 E = FinalOverriders.end();
12337 I != E; ++I) {
12338 for (OverridingMethods::const_iterator OI = I->second.begin(),
12339 OE = I->second.end();
12340 OI != OE; ++OI) {
12341 assert(OI->second.size() > 0 && "no final overrider");
12342 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012343
Richard Smith4ff9ff92012-07-07 06:59:51 +000012344 // C++ [basic.def.odr]p2:
12345 // [...] A virtual member function is used if it is not pure. [...]
12346 if (!Overrider->isPure())
12347 MarkFunctionReferenced(Loc, Overrider);
12348 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012349 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012350
12351 // Only classes that have virtual bases need a VTT.
12352 if (RD->getNumVBases() == 0)
12353 return;
12354
Aaron Ballman574705e2014-03-13 15:41:46 +000012355 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012356 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012357 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012358 if (Base->getNumVBases() == 0)
12359 continue;
12360 MarkVirtualMembersReferenced(Loc, Base);
12361 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012362}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012363
12364/// SetIvarInitializers - This routine builds initialization ASTs for the
12365/// Objective-C implementation whose ivars need be initialized.
12366void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012367 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012368 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012369 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012370 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012371 CollectIvarsToConstructOrDestruct(OID, ivars);
12372 if (ivars.empty())
12373 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012374 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012375 for (unsigned i = 0; i < ivars.size(); i++) {
12376 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012377 if (Field->isInvalidDecl())
12378 continue;
12379
Alexis Hunt1d792652011-01-08 20:30:50 +000012380 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012381 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12382 InitializationKind InitKind =
12383 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012384
12385 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12386 ExprResult MemberInit =
12387 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012388 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012389 // Note, MemberInit could actually come back empty if no initialization
12390 // is required (e.g., because it would call a trivial default constructor)
12391 if (!MemberInit.get() || MemberInit.isInvalid())
12392 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012393
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012394 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012395 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12396 SourceLocation(),
12397 MemberInit.takeAs<Expr>(),
12398 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012399 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012400
12401 // Be sure that the destructor is accessible and is marked as referenced.
12402 if (const RecordType *RecordTy
12403 = Context.getBaseElementType(Field->getType())
12404 ->getAs<RecordType>()) {
12405 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012406 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012407 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012408 CheckDestructorAccess(Field->getLocation(), Destructor,
12409 PDiag(diag::err_access_dtor_ivar)
12410 << Context.getBaseElementType(Field->getType()));
12411 }
12412 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012413 }
12414 ObjCImplementation->setIvarInitializers(Context,
12415 AllToInit.data(), AllToInit.size());
12416 }
12417}
Alexis Hunt6118d662011-05-04 05:57:24 +000012418
Alexis Hunt27a761d2011-05-04 23:29:54 +000012419static
12420void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12421 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12422 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12423 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12424 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012425 if (Ctor->isInvalidDecl())
12426 return;
12427
Richard Smith802c4b72012-08-23 06:16:52 +000012428 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12429
12430 // Target may not be determinable yet, for instance if this is a dependent
12431 // call in an uninstantiated template.
12432 if (Target) {
12433 const FunctionDecl *FNTarget = 0;
12434 (void)Target->hasBody(FNTarget);
12435 Target = const_cast<CXXConstructorDecl*>(
12436 cast_or_null<CXXConstructorDecl>(FNTarget));
12437 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012438
12439 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12440 // Avoid dereferencing a null pointer here.
12441 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12442
12443 if (!Current.insert(Canonical))
12444 return;
12445
12446 // We know that beyond here, we aren't chaining into a cycle.
12447 if (!Target || !Target->isDelegatingConstructor() ||
12448 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012449 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012450 Current.clear();
12451 // We've hit a cycle.
12452 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12453 Current.count(TCanonical)) {
12454 // If we haven't diagnosed this cycle yet, do so now.
12455 if (!Invalid.count(TCanonical)) {
12456 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012457 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012458 << Ctor;
12459
Richard Smith802c4b72012-08-23 06:16:52 +000012460 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012461 if (TCanonical != Canonical)
12462 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12463
12464 CXXConstructorDecl *C = Target;
12465 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012466 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012467 (void)C->getTargetConstructor()->hasBody(FNTarget);
12468 assert(FNTarget && "Ctor cycle through bodiless function");
12469
Richard Smith802c4b72012-08-23 06:16:52 +000012470 C = const_cast<CXXConstructorDecl*>(
12471 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012472 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12473 }
12474 }
12475
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012476 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012477 Current.clear();
12478 } else {
12479 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12480 }
12481}
12482
12483
Alexis Hunt6118d662011-05-04 05:57:24 +000012484void Sema::CheckDelegatingCtorCycles() {
12485 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12486
Douglas Gregorbae31202011-07-27 21:57:17 +000012487 for (DelegatingCtorDeclsType::iterator
12488 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012489 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012490 I != E; ++I)
12491 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012492
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012493 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12494 CE = Invalid.end();
12495 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012496 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012497}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012498
Douglas Gregor3024f072012-04-16 07:05:22 +000012499namespace {
12500 /// \brief AST visitor that finds references to the 'this' expression.
12501 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12502 Sema &S;
12503
12504 public:
12505 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12506
12507 bool VisitCXXThisExpr(CXXThisExpr *E) {
12508 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12509 << E->isImplicit();
12510 return false;
12511 }
12512 };
12513}
12514
12515bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12516 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12517 if (!TSInfo)
12518 return false;
12519
12520 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012521 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012522 if (!ProtoTL)
12523 return false;
12524
12525 // C++11 [expr.prim.general]p3:
12526 // [The expression this] shall not appear before the optional
12527 // cv-qualifier-seq and it shall not appear within the declaration of a
12528 // static member function (although its type and value category are defined
12529 // within a static member function as they are within a non-static member
12530 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012531 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012532 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012533 FindCXXThisExpr Finder(*this);
12534
12535 // If the return type came after the cv-qualifier-seq, check it now.
12536 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012537 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012538 return true;
12539
12540 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012541 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12542 return true;
12543
12544 return checkThisInStaticMemberFunctionAttributes(Method);
12545}
12546
12547bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12548 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12549 if (!TSInfo)
12550 return false;
12551
12552 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012553 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012554 if (!ProtoTL)
12555 return false;
12556
David Blaikie6adc78e2013-02-18 22:06:02 +000012557 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012558 FindCXXThisExpr Finder(*this);
12559
Douglas Gregor3024f072012-04-16 07:05:22 +000012560 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012561 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012562 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012563 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012564 case EST_DynamicNone:
12565 case EST_MSAny:
12566 case EST_None:
12567 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012568
Douglas Gregor3024f072012-04-16 07:05:22 +000012569 case EST_ComputedNoexcept:
12570 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12571 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012572
Douglas Gregor3024f072012-04-16 07:05:22 +000012573 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012574 for (const auto &E : Proto->exceptions()) {
12575 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012576 return true;
12577 }
12578 break;
12579 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012580
12581 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012582}
12583
12584bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12585 FindCXXThisExpr Finder(*this);
12586
12587 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012588 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012589 // FIXME: This should be emitted by tblgen.
12590 Expr *Arg = 0;
12591 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012592 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012593 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012594 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012595 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012596 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012597 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012598 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012599 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012600 else if (const auto *ELF = dyn_cast<ExclusiveLockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012601 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012602 else if (const auto *SLF = dyn_cast<SharedLockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012603 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012604 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012605 Arg = ETLF->getSuccessValue();
12606 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012607 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012608 Arg = STLF->getSuccessValue();
12609 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012610 } else if (const auto *UF = dyn_cast<UnlockFunctionAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012611 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012612 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012613 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012614 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012615 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012616 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012617 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012618 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012619 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012620 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12621 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12622 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012623 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012624
12625 if (Arg && !Finder.TraverseStmt(Arg))
12626 return true;
12627
12628 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12629 if (!Finder.TraverseStmt(Args[I]))
12630 return true;
12631 }
12632 }
12633
12634 return false;
12635}
12636
Douglas Gregor433e0532012-04-16 18:27:27 +000012637void
12638Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12639 ArrayRef<ParsedType> DynamicExceptions,
12640 ArrayRef<SourceRange> DynamicExceptionRanges,
12641 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012642 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012643 FunctionProtoType::ExtProtoInfo &EPI) {
12644 Exceptions.clear();
12645 EPI.ExceptionSpecType = EST;
12646 if (EST == EST_Dynamic) {
12647 Exceptions.reserve(DynamicExceptions.size());
12648 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12649 // FIXME: Preserve type source info.
12650 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12651
12652 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12653 collectUnexpandedParameterPacks(ET, Unexpanded);
12654 if (!Unexpanded.empty()) {
12655 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12656 UPPC_ExceptionType,
12657 Unexpanded);
12658 continue;
12659 }
12660
12661 // Check that the type is valid for an exception spec, and
12662 // drop it if not.
12663 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12664 Exceptions.push_back(ET);
12665 }
12666 EPI.NumExceptions = Exceptions.size();
12667 EPI.Exceptions = Exceptions.data();
12668 return;
12669 }
12670
12671 if (EST == EST_ComputedNoexcept) {
12672 // If an error occurred, there's no expression here.
12673 if (NoexceptExpr) {
12674 assert((NoexceptExpr->isTypeDependent() ||
12675 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12676 Context.BoolTy) &&
12677 "Parser should have made sure that the expression is boolean");
12678 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12679 EPI.ExceptionSpecType = EST_BasicNoexcept;
12680 return;
12681 }
12682
12683 if (!NoexceptExpr->isValueDependent())
12684 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012685 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012686 /*AllowFold*/ false).take();
12687 EPI.NoexceptExpr = NoexceptExpr;
12688 }
12689 return;
12690 }
12691}
12692
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012693/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12694Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12695 // Implicitly declared functions (e.g. copy constructors) are
12696 // __host__ __device__
12697 if (D->isImplicit())
12698 return CFT_HostDevice;
12699
12700 if (D->hasAttr<CUDAGlobalAttr>())
12701 return CFT_Global;
12702
12703 if (D->hasAttr<CUDADeviceAttr>()) {
12704 if (D->hasAttr<CUDAHostAttr>())
12705 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012706 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012707 }
12708
12709 return CFT_Host;
12710}
12711
12712bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12713 CUDAFunctionTarget CalleeTarget) {
12714 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12715 // Callable from the device only."
12716 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12717 return true;
12718
12719 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12720 // Callable from the host only."
12721 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12722 // Callable from the host only."
12723 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12724 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12725 return true;
12726
12727 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12728 return true;
12729
12730 return false;
12731}
John McCall5e77d762013-04-16 07:28:30 +000012732
12733/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12734///
12735MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12736 SourceLocation DeclStart,
12737 Declarator &D, Expr *BitWidth,
12738 InClassInitStyle InitStyle,
12739 AccessSpecifier AS,
12740 AttributeList *MSPropertyAttr) {
12741 IdentifierInfo *II = D.getIdentifier();
12742 if (!II) {
12743 Diag(DeclStart, diag::err_anonymous_property);
12744 return NULL;
12745 }
12746 SourceLocation Loc = D.getIdentifierLoc();
12747
12748 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12749 QualType T = TInfo->getType();
12750 if (getLangOpts().CPlusPlus) {
12751 CheckExtraCXXDefaultArguments(D);
12752
12753 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12754 UPPC_DataMemberType)) {
12755 D.setInvalidType();
12756 T = Context.IntTy;
12757 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12758 }
12759 }
12760
12761 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12762
12763 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12764 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12765 diag::err_invalid_thread)
12766 << DeclSpec::getSpecifierName(TSCS);
12767
12768 // Check to see if this name was declared as a member previously
12769 NamedDecl *PrevDecl = 0;
12770 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12771 LookupName(Previous, S);
12772 switch (Previous.getResultKind()) {
12773 case LookupResult::Found:
12774 case LookupResult::FoundUnresolvedValue:
12775 PrevDecl = Previous.getAsSingle<NamedDecl>();
12776 break;
12777
12778 case LookupResult::FoundOverloaded:
12779 PrevDecl = Previous.getRepresentativeDecl();
12780 break;
12781
12782 case LookupResult::NotFound:
12783 case LookupResult::NotFoundInCurrentInstantiation:
12784 case LookupResult::Ambiguous:
12785 break;
12786 }
12787
12788 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12789 // Maybe we will complain about the shadowed template parameter.
12790 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12791 // Just pretend that we didn't see the previous declaration.
12792 PrevDecl = 0;
12793 }
12794
12795 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12796 PrevDecl = 0;
12797
12798 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012799 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012800 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12801 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012802 ProcessDeclAttributes(TUScope, NewPD, D);
12803 NewPD->setAccess(AS);
12804
12805 if (NewPD->isInvalidDecl())
12806 Record->setInvalidDecl();
12807
12808 if (D.getDeclSpec().isModulePrivateSpecified())
12809 NewPD->setModulePrivate();
12810
12811 if (NewPD->isInvalidDecl() && PrevDecl) {
12812 // Don't introduce NewFD into scope; there's already something
12813 // with the same name in the same scope.
12814 } else if (II) {
12815 PushOnScopeChains(NewPD, S);
12816 } else
12817 Record->addDecl(NewPD);
12818
12819 return NewPD;
12820}