blob: 820f57f5f0cd02f46529ca26f75116d3a343c165 [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.
215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216 EEnd = Proto->exception_end();
217 E != EEnd; ++E)
Richard Smithf623c962012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith938f40b2011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithf623c962012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssonc80a1272009-08-25 02:29:20 +0000251bool
John McCallb268a282010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssonc80a1272009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000273 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275
Richard Smithc406cb72013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlssonc80a1272009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Douglas Gregor758cb672010-10-12 18:23:32 +0000282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000294 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000295}
296
Chris Lattner58258242008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000300void
John McCall48871652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000304 return;
Mike Stump11289f42009-09-09 15:08:12 +0000305
John McCall48871652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner199abbc2008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
John McCallb268a282010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000331}
332
Douglas Gregor58354032008-12-24 00:01:03 +0000333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump11289f42009-09-09 15:08:12 +0000342
John McCall48871652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000346}
347
Douglas Gregor4d87df52008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump11289f42009-09-09 15:08:12 +0000353
John McCall48871652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
396 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000592 if (New->isConstexpr() != Old->isConstexpr()) {
593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594 << New << New->isConstexpr();
595 Diag(Old->getLocation(), diag::note_previous_declaration);
596 Invalid = true;
597 }
598
David Majnemer502b0ed2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000601 // the only declaration of the function or function template in the
602 // translation unit.
603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604 functionDeclHasDefaultArgument(Old)) {
605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606 Diag(Old->getLocation(), diag::note_previous_declaration);
607 Invalid = true;
608 }
609
Douglas Gregorf40863c2010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000612
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000614}
615
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624 return;
625
626 assert(Context.hasSameType(New->getType(), Old->getType()) &&
627 "Should only be called if types are otherwise the same.");
628
629 QualType NewType = New->getType();
630 QualType OldType = Old->getType();
631
632 // We're only interested in pointers and references to functions, as well
633 // as pointers to member functions.
634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635 NewType = R->getPointeeType();
636 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638 NewType = P->getPointeeType();
639 OldType = OldType->getAs<PointerType>()->getPointeeType();
640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641 NewType = M->getPointeeType();
642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643 }
644
645 if (!NewType->isFunctionProtoType())
646 return;
647
648 // There's lots of special cases for functions. For function pointers, system
649 // libraries are hopefully not as broken so that we don't need these
650 // workarounds.
651 if (CheckEquivalentExceptionSpec(
652 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654 New->setInvalidDecl();
655 }
656}
657
Chris Lattner199abbc2008-04-08 05:04:30 +0000658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662 unsigned NumParams = FD->getNumParams();
663 unsigned p;
664
665 // Find first parameter with a default argument
666 for (p = 0; p < NumParams; ++p) {
667 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000669 break;
670 }
671
672 // C++ [dcl.fct.default]p4:
673 // In a given function declaration, all parameters
674 // subsequent to a parameter with a default argument shall
675 // have default arguments supplied in this or previous
676 // declarations. A default argument shall not be redefined
677 // by a later declaration (not even to the same value).
678 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 else
Mike Stump11289f42009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner199abbc2008-04-08 05:04:30 +0000692 LastMissingDefaultArg = p;
693 }
694 }
695
696 if (LastMissingDefaultArg > 0) {
697 // Some default arguments were missing. Clear out all of the
698 // default arguments up to (and including) the last missing
699 // default argument, so that we leave the function parameters
700 // in a semantically valid state.
701 for (p = 0; p <= LastMissingDefaultArg; ++p) {
702 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregor556877c2008-04-13 21:30:24 +0000709
Richard Smitheb3c10c2011-10-01 02:31:28 +0000710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720 SourceLocation ParamLoc = PD->getLocation();
721 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000722 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000723 diag::err_constexpr_non_literal_param,
724 ArgIndex+1, PD->getSourceRange(),
725 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000727 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000728 return true;
729}
730
731/// \brief Get diagnostic %select index for tag kind for
732/// record diagnostic message.
733/// WARNING: Indexes apply to particular diagnostics only!
734///
735/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000737 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000738 case TTK_Struct: return 0;
739 case TTK_Interface: return 1;
740 case TTK_Class: return 2;
741 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000742 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000743}
744
745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746// the requirements of a constexpr function definition or a constexpr
747// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000748// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000749//
Richard Smith3607ffe2012-02-13 03:54:03 +0000750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000754 // C++11 [dcl.constexpr]p4:
755 // The definition of a constexpr constructor shall satisfy the following
756 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000757 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000758 const CXXRecordDecl *RD = MD->getParent();
759 if (RD->getNumVBases()) {
760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761 << isa<CXXConstructorDecl>(NewFD)
762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764 E = RD->vbases_end(); I != E; ++I)
765 Diag(I->getLocStart(),
Richard Smith3607ffe2012-02-13 03:54:03 +0000766 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000767 return false;
768 }
Richard Smith7971b692012-01-13 04:54:00 +0000769 }
770
771 if (!isa<CXXConstructorDecl>(NewFD)) {
772 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 // The definition of a constexpr function shall satisfy the following
774 // constraints:
775 // - it shall not be virtual;
776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779
Richard Smith3607ffe2012-02-13 03:54:03 +0000780 // If it's not obvious why this function is virtual, find an overridden
781 // function which uses the 'virtual' keyword.
782 const CXXMethodDecl *WrittenVirtual = Method;
783 while (!WrittenVirtual->isVirtualAsWritten())
784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785 if (WrittenVirtual != Method)
786 Diag(WrittenVirtual->getLocation(),
787 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000788 return false;
789 }
790
791 // - its return type shall be a literal type;
792 QualType RT = NewFD->getResultType();
793 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000794 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000795 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000797 }
798
Richard Smith7971b692012-01-13 04:54:00 +0000799 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000801 return false;
802
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808///
Richard Smithd9f663b2013-04-22 15:31:51 +0000809/// \return true if the body is OK (maybe only as an extension), false if we
810/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000812 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
815 // contain only
816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818 switch ((*DclIt)->getKind()) {
819 case Decl::StaticAssert:
820 case Decl::Using:
821 case Decl::UsingShadow:
822 case Decl::UsingDirective:
823 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000824 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000825 // - static_assert-declarations
826 // - using-declarations,
827 // - using-directives,
828 continue;
829
830 case Decl::Typedef:
831 case Decl::TypeAlias: {
832 // - typedef declarations and alias-declarations that do not define
833 // classes or enumerations,
834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836 // Don't allow variably-modified types in constexpr functions.
837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839 << TL.getSourceRange() << TL.getType()
840 << isa<CXXConstructorDecl>(Dcl);
841 return false;
842 }
843 continue;
844 }
845
846 case Decl::Enum:
847 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000848 // C++1y allows types to be defined, not just declared.
849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850 SemaRef.Diag(DS->getLocStart(),
851 SemaRef.getLangOpts().CPlusPlus1y
852 ? diag::warn_cxx11_compat_constexpr_type_definition
853 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000854 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000855 continue;
856
Richard Smithd9f663b2013-04-22 15:31:51 +0000857 case Decl::EnumConstant:
858 case Decl::IndirectField:
859 case Decl::ParmVar:
860 // These can only appear with other declarations which are banned in
861 // C++11 and permitted in C++1y, so ignore them.
862 continue;
863
864 case Decl::Var: {
865 // C++1y [dcl.constexpr]p3 allows anything except:
866 // a definition of a variable of non-literal type or of static or
867 // thread storage duration or for which no initialization is performed.
868 VarDecl *VD = cast<VarDecl>(*DclIt);
869 if (VD->isThisDeclarationADefinition()) {
870 if (VD->isStaticLocal()) {
871 SemaRef.Diag(VD->getLocation(),
872 diag::err_constexpr_local_var_static)
873 << isa<CXXConstructorDecl>(Dcl)
874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875 return false;
876 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000877 if (!VD->getType()->isDependentType() &&
878 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000879 VD->getLocation(), VD->getType(),
880 diag::err_constexpr_local_var_non_literal_type,
881 isa<CXXConstructorDecl>(Dcl)))
882 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000883 if (!VD->getType()->isDependentType() &&
884 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000885 SemaRef.Diag(VD->getLocation(),
886 diag::err_constexpr_local_var_no_init)
887 << isa<CXXConstructorDecl>(Dcl);
888 return false;
889 }
890 }
891 SemaRef.Diag(VD->getLocation(),
892 SemaRef.getLangOpts().CPlusPlus1y
893 ? diag::warn_cxx11_compat_constexpr_local_var
894 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000895 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000896 continue;
897 }
898
899 case Decl::NamespaceAlias:
900 case Decl::Function:
901 // These are disallowed in C++11 and permitted in C++1y. Allow them
902 // everywhere as an extension.
903 if (!Cxx1yLoc.isValid())
904 Cxx1yLoc = DS->getLocStart();
905 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906
907 default:
908 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912 }
913
914 return true;
915}
916
917/// Check that the given field is initialized within a constexpr constructor.
918///
919/// \param Dcl The constexpr constructor being checked.
920/// \param Field The field being checked. This may be a member of an anonymous
921/// struct or union nested within the class being checked.
922/// \param Inits All declarations, including anonymous struct/union members and
923/// indirect members, for which any initialization was provided.
924/// \param Diagnosed Set to true if an error is produced.
925static void CheckConstexprCtorInitializer(Sema &SemaRef,
926 const FunctionDecl *Dcl,
927 FieldDecl *Field,
928 llvm::SmallSet<Decl*, 16> &Inits,
929 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000930 if (Field->isInvalidDecl())
931 return;
932
Douglas Gregor556e5862011-10-10 17:22:13 +0000933 if (Field->isUnnamedBitfield())
934 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000935
Richard Smithab44d5b2013-12-10 08:25:00 +0000936 // Anonymous unions with no variant members and empty anonymous structs do not
937 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
938 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000939 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000940 (Field->getType()->isUnionType()
941 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
942 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000943 return;
944
Richard Smitheb3c10c2011-10-01 02:31:28 +0000945 if (!Inits.count(Field)) {
946 if (!Diagnosed) {
947 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
948 Diagnosed = true;
949 }
950 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
951 } else if (Field->isAnonymousStructOrUnion()) {
952 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
953 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
954 I != E; ++I)
955 // If an anonymous union contains an anonymous struct of which any member
956 // is initialized, all members must be initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000957 if (!RD->isUnion() || Inits.count(*I))
958 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 }
960}
961
Richard Smithd9f663b2013-04-22 15:31:51 +0000962/// Check the provided statement is allowed in a constexpr function
963/// definition.
964static bool
965CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000966 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000967 SourceLocation &Cxx1yLoc) {
968 // - its function-body shall be [...] a compound-statement that contains only
969 switch (S->getStmtClass()) {
970 case Stmt::NullStmtClass:
971 // - null statements,
972 return true;
973
974 case Stmt::DeclStmtClass:
975 // - static_assert-declarations
976 // - using-declarations,
977 // - using-directives,
978 // - typedef declarations and alias-declarations that do not define
979 // classes or enumerations,
980 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
981 return false;
982 return true;
983
984 case Stmt::ReturnStmtClass:
985 // - and exactly one return statement;
986 if (isa<CXXConstructorDecl>(Dcl)) {
987 // C++1y allows return statements in constexpr constructors.
988 if (!Cxx1yLoc.isValid())
989 Cxx1yLoc = S->getLocStart();
990 return true;
991 }
992
993 ReturnStmts.push_back(S->getLocStart());
994 return true;
995
996 case Stmt::CompoundStmtClass: {
997 // C++1y allows compound-statements.
998 if (!Cxx1yLoc.isValid())
999 Cxx1yLoc = S->getLocStart();
1000
1001 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1002 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1003 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1004 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1005 Cxx1yLoc))
1006 return false;
1007 }
1008 return true;
1009 }
1010
1011 case Stmt::AttributedStmtClass:
1012 if (!Cxx1yLoc.isValid())
1013 Cxx1yLoc = S->getLocStart();
1014 return true;
1015
1016 case Stmt::IfStmtClass: {
1017 // C++1y allows if-statements.
1018 if (!Cxx1yLoc.isValid())
1019 Cxx1yLoc = S->getLocStart();
1020
1021 IfStmt *If = cast<IfStmt>(S);
1022 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1023 Cxx1yLoc))
1024 return false;
1025 if (If->getElse() &&
1026 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1027 Cxx1yLoc))
1028 return false;
1029 return true;
1030 }
1031
1032 case Stmt::WhileStmtClass:
1033 case Stmt::DoStmtClass:
1034 case Stmt::ForStmtClass:
1035 case Stmt::CXXForRangeStmtClass:
1036 case Stmt::ContinueStmtClass:
1037 // C++1y allows all of these. We don't allow them as extensions in C++11,
1038 // because they don't make sense without variable mutation.
1039 if (!SemaRef.getLangOpts().CPlusPlus1y)
1040 break;
1041 if (!Cxx1yLoc.isValid())
1042 Cxx1yLoc = S->getLocStart();
1043 for (Stmt::child_range Children = S->children(); Children; ++Children)
1044 if (*Children &&
1045 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1046 Cxx1yLoc))
1047 return false;
1048 return true;
1049
1050 case Stmt::SwitchStmtClass:
1051 case Stmt::CaseStmtClass:
1052 case Stmt::DefaultStmtClass:
1053 case Stmt::BreakStmtClass:
1054 // C++1y allows switch-statements, and since they don't need variable
1055 // mutation, we can reasonably allow them in C++11 as an extension.
1056 if (!Cxx1yLoc.isValid())
1057 Cxx1yLoc = S->getLocStart();
1058 for (Stmt::child_range Children = S->children(); Children; ++Children)
1059 if (*Children &&
1060 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1061 Cxx1yLoc))
1062 return false;
1063 return true;
1064
1065 default:
1066 if (!isa<Expr>(S))
1067 break;
1068
1069 // C++1y allows expression-statements.
1070 if (!Cxx1yLoc.isValid())
1071 Cxx1yLoc = S->getLocStart();
1072 return true;
1073 }
1074
1075 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1076 << isa<CXXConstructorDecl>(Dcl);
1077 return false;
1078}
1079
Richard Smitheb3c10c2011-10-01 02:31:28 +00001080/// Check the body for the given constexpr function declaration only contains
1081/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1082///
1083/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001084bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001085 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001086 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001087 // The definition of a constexpr function shall satisfy the following
1088 // constraints: [...]
1089 // - its function-body shall be = delete, = default, or a
1090 // compound-statement
1091 //
Richard Smith74388b42012-02-04 00:33:54 +00001092 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001093 // In the definition of a constexpr constructor, [...]
1094 // - its function-body shall not be a function-try-block;
1095 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1096 << isa<CXXConstructorDecl>(Dcl);
1097 return false;
1098 }
1099
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001100 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001101
1102 // - its function-body shall be [...] a compound-statement that contains only
1103 // [... list of cases ...]
1104 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1105 SourceLocation Cxx1yLoc;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001106 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1107 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001108 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1109 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001110 }
1111
Richard Smithd9f663b2013-04-22 15:31:51 +00001112 if (Cxx1yLoc.isValid())
1113 Diag(Cxx1yLoc,
1114 getLangOpts().CPlusPlus1y
1115 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1116 : diag::ext_constexpr_body_invalid_stmt)
1117 << isa<CXXConstructorDecl>(Dcl);
1118
Richard Smitheb3c10c2011-10-01 02:31:28 +00001119 if (const CXXConstructorDecl *Constructor
1120 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1121 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001122 // DR1359:
1123 // - every non-variant non-static data member and base class sub-object
1124 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001125 // DR1460:
1126 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001127 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001128 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001129 if (Constructor->getNumCtorInitializers() == 0 &&
1130 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001131 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1132 return false;
1133 }
Richard Smithf368fb42011-10-10 16:38:04 +00001134 } else if (!Constructor->isDependentContext() &&
1135 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001136 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1137
1138 // Skip detailed checking if we have enough initializers, and we would
1139 // allow at most one initializer per member.
1140 bool AnyAnonStructUnionMembers = false;
1141 unsigned Fields = 0;
1142 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1143 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001144 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001145 AnyAnonStructUnionMembers = true;
1146 break;
1147 }
1148 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001149 // DR1460:
1150 // - if the class is a union-like class, but is not a union, for each of
1151 // its anonymous union members having variant members, exactly one of
1152 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001153 if (AnyAnonStructUnionMembers ||
1154 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1155 // Check initialization of non-static data members. Base classes are
1156 // always initialized so do not need to be checked. Dependent bases
1157 // might not have initializers in the member initializer list.
1158 llvm::SmallSet<Decl*, 16> Inits;
1159 for (CXXConstructorDecl::init_const_iterator
1160 I = Constructor->init_begin(), E = Constructor->init_end();
1161 I != E; ++I) {
1162 if (FieldDecl *FD = (*I)->getMember())
1163 Inits.insert(FD);
1164 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
1169 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1170 E = RD->field_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001171 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001172 if (Diagnosed)
1173 return false;
1174 }
1175 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001176 } else {
1177 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001178 // C++1y doesn't require constexpr functions to contain a 'return'
1179 // statement. We still do, unless the return type is void, because
1180 // otherwise if there's no return statement, the function cannot
1181 // be used in a core constant expression.
Richard Smith3da88fa2013-04-26 14:36:30 +00001182 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001183 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001184 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1185 : diag::err_constexpr_body_no_return);
1186 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001187 }
1188 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001189 Diag(ReturnStmts.back(),
1190 getLangOpts().CPlusPlus1y
1191 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1192 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1194 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001195 }
1196 }
1197
Richard Smith74388b42012-02-04 00:33:54 +00001198 // C++11 [dcl.constexpr]p5:
1199 // if no function argument values exist such that the function invocation
1200 // substitution would produce a constant expression, the program is
1201 // ill-formed; no diagnostic required.
1202 // C++11 [dcl.constexpr]p3:
1203 // - every constructor call and implicit conversion used in initializing the
1204 // return value shall be one of those allowed in a constant expression.
1205 // C++11 [dcl.constexpr]p4:
1206 // - every constructor involved in initializing non-static data members and
1207 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001208 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001209 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001210 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001211 << isa<CXXConstructorDecl>(Dcl);
1212 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1213 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001214 // Don't return false here: we allow this for compatibility in
1215 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001216 }
1217
Richard Smitheb3c10c2011-10-01 02:31:28 +00001218 return true;
1219}
1220
Douglas Gregor61956c42008-10-31 09:07:45 +00001221/// isCurrentClassName - Determine whether the identifier II is the
1222/// name of the class type currently being defined. In the case of
1223/// nested classes, this will only return true if II is the name of
1224/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001225bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1226 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001228
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001229 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001230 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001231 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1233 } else
1234 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1235
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001236 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001237 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001238 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001239}
1240
Richard Smithfb8b7b92013-10-15 00:00:26 +00001241/// \brief Determine whether the identifier II is a typo for the name of
1242/// the class type currently being defined. If so, update it to the identifier
1243/// that should have been used.
1244bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1245 assert(getLangOpts().CPlusPlus && "No class names in C!");
1246
1247 if (!getLangOpts().SpellChecking)
1248 return false;
1249
1250 CXXRecordDecl *CurDecl;
1251 if (SS && SS->isSet() && !SS->isInvalid()) {
1252 DeclContext *DC = computeDeclContext(*SS, true);
1253 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1254 } else
1255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1256
1257 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1258 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1259 < II->getLength()) {
1260 II = CurDecl->getIdentifier();
1261 return true;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc974572012-11-10 07:24:09 +00001267/// \brief Determine whether the given class is a base class of the given
1268/// class, including looking at dependent bases.
1269static bool findCircularInheritance(const CXXRecordDecl *Class,
1270 const CXXRecordDecl *Current) {
1271 SmallVector<const CXXRecordDecl*, 8> Queue;
1272
1273 Class = Class->getCanonicalDecl();
1274 while (true) {
1275 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1276 E = Current->bases_end();
1277 I != E; ++I) {
1278 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1279 if (!Base)
1280 continue;
1281
1282 Base = Base->getDefinition();
1283 if (!Base)
1284 continue;
1285
1286 if (Base->getCanonicalDecl() == Class)
1287 return true;
1288
1289 Queue.push_back(Base);
1290 }
1291
1292 if (Queue.empty())
1293 return false;
1294
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001295 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001296 }
1297
1298 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001299}
1300
Mike Stump11289f42009-09-09 15:08:12 +00001301/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001302///
1303/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1304/// and returns NULL otherwise.
1305CXXBaseSpecifier *
1306Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1307 SourceRange SpecifierRange,
1308 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001309 TypeSourceInfo *TInfo,
1310 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001311 QualType BaseType = TInfo->getType();
1312
Douglas Gregor463421d2009-03-03 04:44:36 +00001313 // C++ [class.union]p1:
1314 // A union shall not have base classes.
1315 if (Class->isUnion()) {
1316 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1317 << SpecifierRange;
1318 return 0;
1319 }
1320
Douglas Gregor752a5952011-01-03 22:36:02 +00001321 if (EllipsisLoc.isValid() &&
1322 !TInfo->getType()->containsUnexpandedParameterPack()) {
1323 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1324 << TInfo->getTypeLoc().getSourceRange();
1325 EllipsisLoc = SourceLocation();
1326 }
Douglas Gregor62004702012-11-10 01:18:17 +00001327
1328 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1329
1330 if (BaseType->isDependentType()) {
1331 // Make sure that we don't have circular inheritance among our dependent
1332 // bases. For non-dependent bases, the check for completeness below handles
1333 // this.
1334 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1335 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1336 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001337 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001338 Diag(BaseLoc, diag::err_circular_inheritance)
1339 << BaseType << Context.getTypeDeclType(Class);
1340
1341 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1342 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1343 << BaseType;
1344
1345 return 0;
1346 }
1347 }
1348
Mike Stump11289f42009-09-09 15:08:12 +00001349 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001350 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001351 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001352 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001353
1354 // Base specifiers must be record types.
1355 if (!BaseType->isRecordType()) {
1356 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1357 return 0;
1358 }
1359
1360 // C++ [class.union]p1:
1361 // A union shall not be used as a base class.
1362 if (BaseType->isUnionType()) {
1363 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1364 return 0;
1365 }
1366
1367 // C++ [class.derived]p2:
1368 // The class-name in a base-specifier shall not be an incompletely
1369 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001370 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001371 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001372 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001373 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001374 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001375
Eli Friedmanc96d4962009-08-15 21:55:26 +00001376 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001377 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001378 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001379 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001380 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001381 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001382 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001383
David Majnemer9b1754d2013-11-02 12:00:36 +00001384 // A class which contains a flexible array member is not suitable for use as a
1385 // base class:
1386 // - If the layout determines that a base comes before another base,
1387 // the flexible array member would index into the subsequent base.
1388 // - If the layout determines that base comes before the derived class,
1389 // the flexible array member would index into the derived class.
1390 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1391 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1392 << CXXBaseDecl->getDeclName();
1393 return 0;
1394 }
1395
Anders Carlsson65c76d32011-03-25 14:55:14 +00001396 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001397 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001398 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001399 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001400 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001401 << CXXBaseDecl->getDeclName()
1402 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001403 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1404 << CXXBaseDecl->getDeclName();
1405 return 0;
1406 }
1407
John McCall3696dcb2010-08-17 07:23:57 +00001408 if (BaseDecl->isInvalidDecl())
1409 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001410
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001411 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001412 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001413 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001414 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001415}
1416
Douglas Gregor556877c2008-04-13 21:30:24 +00001417/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1418/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001419/// example:
1420/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001421/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001422BaseResult
John McCall48871652010-08-21 09:40:31 +00001423Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001424 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001425 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001426 ParsedType basetype, SourceLocation BaseLoc,
1427 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001428 if (!classdecl)
1429 return true;
1430
Douglas Gregorc40290e2009-03-09 23:48:35 +00001431 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001432 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001433 if (!Class)
1434 return true;
1435
Richard Smith4c96e992013-02-19 23:47:15 +00001436 // We do not support any C++11 attributes on base-specifiers yet.
1437 // Diagnose any attributes we see.
1438 if (!Attributes.empty()) {
1439 for (AttributeList *Attr = Attributes.getList(); Attr;
1440 Attr = Attr->getNext()) {
1441 if (Attr->isInvalid() ||
1442 Attr->getKind() == AttributeList::IgnoredAttribute)
1443 continue;
1444 Diag(Attr->getLoc(),
1445 Attr->getKind() == AttributeList::UnknownAttribute
1446 ? diag::warn_unknown_attribute_ignored
1447 : diag::err_base_specifier_attribute)
1448 << Attr->getName();
1449 }
1450 }
1451
Nick Lewycky19b9f952010-07-26 16:56:01 +00001452 TypeSourceInfo *TInfo = 0;
1453 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001454
Douglas Gregor752a5952011-01-03 22:36:02 +00001455 if (EllipsisLoc.isInvalid() &&
1456 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001457 UPPC_BaseType))
1458 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001459
Douglas Gregor463421d2009-03-03 04:44:36 +00001460 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001461 Virtual, Access, TInfo,
1462 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001463 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001464 else
1465 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001466
Douglas Gregor463421d2009-03-03 04:44:36 +00001467 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001468}
Douglas Gregor556877c2008-04-13 21:30:24 +00001469
Douglas Gregor463421d2009-03-03 04:44:36 +00001470/// \brief Performs the actual work of attaching the given base class
1471/// specifiers to a C++ class.
1472bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1473 unsigned NumBases) {
1474 if (NumBases == 0)
1475 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001476
1477 // Used to keep track of which base types we have already seen, so
1478 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001479 // that the key is always the unqualified canonical type of the base
1480 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001481 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1482
1483 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001484 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001485 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001486 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001487 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001488 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001489 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001490
1491 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1492 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001493 // C++ [class.mi]p3:
1494 // A class shall not be specified as a direct base class of a
1495 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001496 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001497 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001498 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001499 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001500
1501 // Delete the duplicate base class specifier; we're going to
1502 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001503 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001504
1505 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001506 } else {
1507 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001508 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001509 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001510 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1511 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1512 if (Class->isInterface() &&
1513 (!RD->isInterface() ||
1514 KnownBase->getAccessSpecifier() != AS_public)) {
1515 // The Microsoft extension __interface does not permit bases that
1516 // are not themselves public interfaces.
1517 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1518 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1519 << RD->getSourceRange();
1520 Invalid = true;
1521 }
1522 if (RD->hasAttr<WeakAttr>())
1523 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1524 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001525 }
1526 }
1527
1528 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001529 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001530
1531 // Delete the remaining (good) base class specifiers, since their
1532 // data has been copied into the CXXRecordDecl.
1533 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001534 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001535
1536 return Invalid;
1537}
1538
1539/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1540/// class, after checking whether there are any duplicate base
1541/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001542void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001543 unsigned NumBases) {
1544 if (!ClassDecl || !Bases || !NumBases)
1545 return;
1546
1547 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001548 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001549}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001550
Douglas Gregor36d1b142009-10-06 17:59:45 +00001551/// \brief Determine whether the type \p Derived is a C++ class that is
1552/// derived from the type \p Base.
1553bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001554 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001555 return false;
John McCalle78aac42010-03-10 03:28:59 +00001556
Douglas Gregor45bb4832013-03-26 23:36:30 +00001557 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001558 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001559 return false;
1560
Douglas Gregor45bb4832013-03-26 23:36:30 +00001561 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001562 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001563 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001564
1565 // If either the base or the derived type is invalid, don't try to
1566 // check whether one is derived from the other.
1567 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1568 return false;
1569
John McCall67da35c2010-02-04 22:26:26 +00001570 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1571 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001572}
1573
1574/// \brief Determine whether the type \p Derived is a C++ class that is
1575/// derived from the type \p Base.
1576bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001577 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001578 return false;
1579
Douglas Gregor45bb4832013-03-26 23:36:30 +00001580 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001581 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001582 return false;
1583
Douglas Gregor45bb4832013-03-26 23:36:30 +00001584 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001585 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001586 return false;
1587
Douglas Gregor36d1b142009-10-06 17:59:45 +00001588 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1589}
1590
Anders Carlssona70cff62010-04-24 19:06:50 +00001591void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001592 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001593 assert(BasePathArray.empty() && "Base path array must be empty!");
1594 assert(Paths.isRecordingPaths() && "Must record paths!");
1595
1596 const CXXBasePath &Path = Paths.front();
1597
1598 // We first go backward and check if we have a virtual base.
1599 // FIXME: It would be better if CXXBasePath had the base specifier for
1600 // the nearest virtual base.
1601 unsigned Start = 0;
1602 for (unsigned I = Path.size(); I != 0; --I) {
1603 if (Path[I - 1].Base->isVirtual()) {
1604 Start = I - 1;
1605 break;
1606 }
1607 }
1608
1609 // Now add all bases.
1610 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001611 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001612}
1613
Douglas Gregor88d292c2010-05-13 16:44:06 +00001614/// \brief Determine whether the given base path includes a virtual
1615/// base class.
John McCallcf142162010-08-07 06:22:56 +00001616bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1617 for (CXXCastPath::const_iterator B = BasePath.begin(),
1618 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001619 B != BEnd; ++B)
1620 if ((*B)->isVirtual())
1621 return true;
1622
1623 return false;
1624}
1625
Douglas Gregor36d1b142009-10-06 17:59:45 +00001626/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1627/// conversion (where Derived and Base are class types) is
1628/// well-formed, meaning that the conversion is unambiguous (and
1629/// that all of the base classes are accessible). Returns true
1630/// and emits a diagnostic if the code is ill-formed, returns false
1631/// otherwise. Loc is the location where this routine should point to
1632/// if there is an error, and Range is the source range to highlight
1633/// if there is an error.
1634bool
1635Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001636 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001637 unsigned AmbigiousBaseConvID,
1638 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001639 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001640 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001641 // First, determine whether the path from Derived to Base is
1642 // ambiguous. This is slightly more expensive than checking whether
1643 // the Derived to Base conversion exists, because here we need to
1644 // explore multiple paths to determine if there is an ambiguity.
1645 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1646 /*DetectVirtual=*/false);
1647 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1648 assert(DerivationOkay &&
1649 "Can only be used with a derived-to-base conversion");
1650 (void)DerivationOkay;
1651
1652 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001653 if (InaccessibleBaseID) {
1654 // Check that the base class can be accessed.
1655 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1656 InaccessibleBaseID)) {
1657 case AR_inaccessible:
1658 return true;
1659 case AR_accessible:
1660 case AR_dependent:
1661 case AR_delayed:
1662 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001663 }
John McCall5b0829a2010-02-10 09:31:12 +00001664 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001665
1666 // Build a base path if necessary.
1667 if (BasePath)
1668 BuildBasePathArray(Paths, *BasePath);
1669 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001670 }
1671
David Majnemer626032f2013-06-22 06:43:58 +00001672 if (AmbigiousBaseConvID) {
1673 // We know that the derived-to-base conversion is ambiguous, and
1674 // we're going to produce a diagnostic. Perform the derived-to-base
1675 // search just one more time to compute all of the possible paths so
1676 // that we can print them out. This is more expensive than any of
1677 // the previous derived-to-base checks we've done, but at this point
1678 // performance isn't as much of an issue.
1679 Paths.clear();
1680 Paths.setRecordingPaths(true);
1681 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1682 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1683 (void)StillOkay;
1684
1685 // Build up a textual representation of the ambiguous paths, e.g.,
1686 // D -> B -> A, that will be used to illustrate the ambiguous
1687 // conversions in the diagnostic. We only print one of the paths
1688 // to each base class subobject.
1689 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1690
1691 Diag(Loc, AmbigiousBaseConvID)
1692 << Derived << Base << PathDisplayStr << Range << Name;
1693 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 return true;
1695}
1696
1697bool
1698Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001699 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001700 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001701 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001702 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001703 IgnoreAccess ? 0
1704 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001706 Loc, Range, DeclarationName(),
1707 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001708}
1709
1710
1711/// @brief Builds a string representing ambiguous paths from a
1712/// specific derived class to different subobjects of the same base
1713/// class.
1714///
1715/// This function builds a string that can be used in error messages
1716/// to show the different paths that one can take through the
1717/// inheritance hierarchy to go from the derived class to different
1718/// subobjects of a base class. The result looks something like this:
1719/// @code
1720/// struct D -> struct B -> struct A
1721/// struct D -> struct C -> struct A
1722/// @endcode
1723std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1724 std::string PathDisplayStr;
1725 std::set<unsigned> DisplayedPaths;
1726 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1727 Path != Paths.end(); ++Path) {
1728 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1729 // We haven't displayed a path to this particular base
1730 // class subobject yet.
1731 PathDisplayStr += "\n ";
1732 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1733 for (CXXBasePath::const_iterator Element = Path->begin();
1734 Element != Path->end(); ++Element)
1735 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1736 }
1737 }
1738
1739 return PathDisplayStr;
1740}
1741
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001742//===----------------------------------------------------------------------===//
1743// C++ class member Handling
1744//===----------------------------------------------------------------------===//
1745
Abramo Bagnarad7340582010-06-05 05:09:32 +00001746/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001747bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1748 SourceLocation ASLoc,
1749 SourceLocation ColonLoc,
1750 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001751 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001752 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001753 ASLoc, ColonLoc);
1754 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001755 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001756}
1757
Richard Smith18f07db2012-08-06 03:25:17 +00001758/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001759void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001760 if (D->isInvalidDecl())
1761 return;
1762
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001763 // We only care about "override" and "final" declarations.
1764 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1765 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001766
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001767 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001768
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001769 // We can't check dependent instance methods.
1770 if (MD && MD->isInstance() &&
1771 (MD->getParent()->hasAnyDependentBases() ||
1772 MD->getType()->isDependentType()))
1773 return;
1774
1775 if (MD && !MD->isVirtual()) {
1776 // If we have a non-virtual method, check if if hides a virtual method.
1777 // (In that case, it's most likely the method has the wrong type.)
1778 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1779 FindHiddenVirtualMethods(MD, OverloadedMethods);
1780
1781 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001782 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1783 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001784 diag::override_keyword_hides_virtual_member_function)
1785 << "override" << (OverloadedMethods.size() > 1);
1786 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001787 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001788 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001789 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1790 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001791 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001792 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1793 MD->setInvalidDecl();
1794 return;
1795 }
1796 // Fall through into the general case diagnostic.
1797 // FIXME: We might want to attempt typo correction here.
1798 }
1799
1800 if (!MD || !MD->isVirtual()) {
1801 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1802 Diag(OA->getLocation(),
1803 diag::override_keyword_only_allowed_on_virtual_member_functions)
1804 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1805 D->dropAttr<OverrideAttr>();
1806 }
1807 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1808 Diag(FA->getLocation(),
1809 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001810 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1811 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001812 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001813 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001814 return;
1815 }
Richard Smith18f07db2012-08-06 03:25:17 +00001816
Richard Smith18f07db2012-08-06 03:25:17 +00001817 // C++11 [class.virtual]p5:
1818 // If a virtual function is marked with the virt-specifier override and
1819 // does not override a member function of a base class, the program is
1820 // ill-formed.
1821 bool HasOverriddenMethods =
1822 MD->begin_overridden_methods() != MD->end_overridden_methods();
1823 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1824 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1825 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001826}
1827
Richard Smith18f07db2012-08-06 03:25:17 +00001828/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001829/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001830/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001831bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1832 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001833 FinalAttr *FA = Old->getAttr<FinalAttr>();
1834 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001835 return false;
1836
1837 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001838 << New->getDeclName()
1839 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001840 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1841 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001842}
1843
Daniel Jasper0baec5492012-06-06 08:32:04 +00001844static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001845 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1846 // FIXME: Destruction of ObjC lifetime types has side-effects.
1847 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1848 return !RD->isCompleteDefinition() ||
1849 !RD->hasTrivialDefaultConstructor() ||
1850 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001851 return false;
1852}
1853
John McCall5e77d762013-04-16 07:28:30 +00001854static AttributeList *getMSPropertyAttr(AttributeList *list) {
1855 for (AttributeList* it = list; it != 0; it = it->getNext())
1856 if (it->isDeclspecPropertyAttribute())
1857 return it;
1858 return 0;
1859}
1860
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001861/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1862/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001863/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001864/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1865/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001866NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001867Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001868 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001869 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001870 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001871 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001872 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1873 DeclarationName Name = NameInfo.getName();
1874 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001875
1876 // For anonymous bitfields, the location should point to the type.
1877 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001878 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001879
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001880 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001881
John McCallb1cd7da2010-06-04 08:34:12 +00001882 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001883 assert(!DS.isFriendSpecified());
1884
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001885 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001886
John McCalldb632ac2012-09-25 07:32:39 +00001887 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1888 // The Microsoft extension __interface only permits public member functions
1889 // and prohibits constructors, destructors, operators, non-public member
1890 // functions, static methods and data members.
1891 unsigned InvalidDecl;
1892 bool ShowDeclName = true;
1893 if (!isFunc)
1894 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1895 else if (AS != AS_public)
1896 InvalidDecl = 2;
1897 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1898 InvalidDecl = 3;
1899 else switch (Name.getNameKind()) {
1900 case DeclarationName::CXXConstructorName:
1901 InvalidDecl = 4;
1902 ShowDeclName = false;
1903 break;
1904
1905 case DeclarationName::CXXDestructorName:
1906 InvalidDecl = 5;
1907 ShowDeclName = false;
1908 break;
1909
1910 case DeclarationName::CXXOperatorName:
1911 case DeclarationName::CXXConversionFunctionName:
1912 InvalidDecl = 6;
1913 break;
1914
1915 default:
1916 InvalidDecl = 0;
1917 break;
1918 }
1919
1920 if (InvalidDecl) {
1921 if (ShowDeclName)
1922 Diag(Loc, diag::err_invalid_member_in_interface)
1923 << (InvalidDecl-1) << Name;
1924 else
1925 Diag(Loc, diag::err_invalid_member_in_interface)
1926 << (InvalidDecl-1) << "";
1927 return 0;
1928 }
1929 }
1930
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001931 // C++ 9.2p6: A member shall not be declared to have automatic storage
1932 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001933 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1934 // data members and cannot be applied to names declared const or static,
1935 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001936 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001937 case DeclSpec::SCS_unspecified:
1938 case DeclSpec::SCS_typedef:
1939 case DeclSpec::SCS_static:
1940 break;
1941 case DeclSpec::SCS_mutable:
1942 if (isFunc) {
1943 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001944
Richard Smithb4a9e862013-04-12 22:46:28 +00001945 // FIXME: It would be nicer if the keyword was ignored only for this
1946 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001947 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001948 }
1949 break;
1950 default:
1951 Diag(DS.getStorageClassSpecLoc(),
1952 diag::err_storageclass_invalid_for_member);
1953 D.getMutableDeclSpec().ClearStorageClassSpecs();
1954 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001955 }
1956
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001957 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1958 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001959 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001960
David Blaikie35506f82013-01-30 01:22:18 +00001961 if (DS.isConstexprSpecified() && isInstField) {
1962 SemaDiagnosticBuilder B =
1963 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1964 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1965 if (InitStyle == ICIS_NoInit) {
1966 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1967 D.getMutableDeclSpec().ClearConstexprSpec();
1968 const char *PrevSpec;
1969 unsigned DiagID;
1970 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1971 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001972 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001973 assert(!Failed && "Making a constexpr member const shouldn't fail");
1974 } else {
1975 B << 1;
1976 const char *PrevSpec;
1977 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001978 if (D.getMutableDeclSpec().SetStorageClassSpec(
1979 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001980 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001981 "This is the only DeclSpec that should fail to be applied");
1982 B << 1;
1983 } else {
1984 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1985 isInstField = false;
1986 }
1987 }
1988 }
1989
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001990 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001991 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001992 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001993
1994 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001995 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001996 Diag(Loc, diag::err_bad_variable_name)
1997 << Name;
1998 return 0;
1999 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002000
Benjamin Kramer365082d2012-05-19 16:34:46 +00002001 IdentifierInfo *II = Name.getAsIdentifierInfo();
2002
Douglas Gregor7c26c042011-09-21 14:40:46 +00002003 // Member field could not be with "template" keyword.
2004 // So TemplateParameterLists should be empty in this case.
2005 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002006 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002007 if (TemplateParams->size()) {
2008 // There is no such thing as a member field template.
2009 Diag(D.getIdentifierLoc(), diag::err_template_member)
2010 << II
2011 << SourceRange(TemplateParams->getTemplateLoc(),
2012 TemplateParams->getRAngleLoc());
2013 } else {
2014 // There is an extraneous 'template<>' for this member.
2015 Diag(TemplateParams->getTemplateLoc(),
2016 diag::err_template_member_noparams)
2017 << II
2018 << SourceRange(TemplateParams->getTemplateLoc(),
2019 TemplateParams->getRAngleLoc());
2020 }
2021 return 0;
2022 }
2023
Douglas Gregora007d362010-10-13 22:19:53 +00002024 if (SS.isSet() && !SS.isInvalid()) {
2025 // The user provided a superfluous scope specifier inside a class
2026 // definition:
2027 //
2028 // class X {
2029 // int X::member;
2030 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002031 if (DeclContext *DC = computeDeclContext(SS, false))
2032 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002033 else
2034 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2035 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002036
Douglas Gregora007d362010-10-13 22:19:53 +00002037 SS.clear();
2038 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002039
John McCall5e77d762013-04-16 07:28:30 +00002040 AttributeList *MSPropertyAttr =
2041 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002042 if (MSPropertyAttr) {
2043 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2044 BitWidth, InitStyle, AS, MSPropertyAttr);
2045 if (!Member)
2046 return 0;
2047 isInstField = false;
2048 } else {
2049 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2050 BitWidth, InitStyle, AS);
2051 assert(Member && "HandleField never returns null");
2052 }
2053 } else {
2054 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2055
2056 Member = HandleDeclarator(S, D, TemplateParameterLists);
2057 if (!Member)
2058 return 0;
2059
2060 // Non-instance-fields can't have a bitfield.
2061 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002062 if (Member->isInvalidDecl()) {
2063 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002064 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002065 // C++ 9.6p3: A bit-field shall not be a static member.
2066 // "static member 'A' cannot be a bit-field"
2067 Diag(Loc, diag::err_static_not_bitfield)
2068 << Name << BitWidth->getSourceRange();
2069 } else if (isa<TypedefDecl>(Member)) {
2070 // "typedef member 'x' cannot be a bit-field"
2071 Diag(Loc, diag::err_typedef_not_bitfield)
2072 << Name << BitWidth->getSourceRange();
2073 } else {
2074 // A function typedef ("typedef int f(); f a;").
2075 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2076 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002077 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002078 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002079 }
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattnerd26760a2009-03-05 23:01:03 +00002081 BitWidth = 0;
2082 Member->setInvalidDecl();
2083 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002084
2085 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002086
Larisse Voufo39a1e502013-08-06 01:03:05 +00002087 // If we have declared a member function template or static data member
2088 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002089 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2090 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002091 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2092 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002093 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002094
Richard Smith18f07db2012-08-06 03:25:17 +00002095 if (VS.isOverrideSpecified())
2096 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2097 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002098 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2099 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002100
Douglas Gregorf2f08062011-03-08 17:10:18 +00002101 if (VS.getLastLocation().isValid()) {
2102 // Update the end location of a method that has a virt-specifiers.
2103 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2104 MD->setRangeEnd(VS.getLastLocation());
2105 }
Richard Smith18f07db2012-08-06 03:25:17 +00002106
Anders Carlssonc87f8612011-01-20 06:29:02 +00002107 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002108
Douglas Gregor92751d42008-11-17 22:58:34 +00002109 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002110
Daniel Jasper0baec5492012-06-06 08:32:04 +00002111 if (isInstField) {
2112 FieldDecl *FD = cast<FieldDecl>(Member);
2113 FieldCollector->Add(FD);
2114
2115 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2116 FD->getLocation())
2117 != DiagnosticsEngine::Ignored) {
2118 // Remember all explicit private FieldDecls that have a name, no side
2119 // effects and are not part of a dependent type declaration.
2120 if (!FD->isImplicit() && FD->getDeclName() &&
2121 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002122 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002123 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002124 !InitializationHasSideEffects(*FD))
2125 UnusedPrivateFields.insert(FD);
2126 }
2127 }
2128
John McCall48871652010-08-21 09:40:31 +00002129 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002130}
2131
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002132namespace {
2133 class UninitializedFieldVisitor
2134 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2135 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002136 // List of Decls to generate a warning on. Also remove Decls that become
2137 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002138 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002139 // If non-null, add a note to the warning pointing back to the constructor.
2140 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002141 public:
2142 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002143 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002144 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002145 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002146 : Inherited(S.Context), S(S), Decls(Decls),
2147 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002148
Richard Trieufd687772013-09-16 20:46:50 +00002149 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002150 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2151 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002152
Richard Trieu1bc22c12013-09-13 03:20:53 +00002153 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2154 // or union.
2155 MemberExpr *FieldME = ME;
2156
2157 Expr *Base = ME;
2158 while (isa<MemberExpr>(Base)) {
2159 ME = cast<MemberExpr>(Base);
2160
2161 if (isa<VarDecl>(ME->getMemberDecl()))
2162 return;
2163
2164 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2165 if (!FD->isAnonymousStructOrUnion())
2166 FieldME = ME;
2167
2168 Base = ME->getBase();
2169 }
2170
Richard Trieufd687772013-09-16 20:46:50 +00002171 if (!isa<CXXThisExpr>(Base))
2172 return;
2173
Richard Trieu406e65c2013-09-20 03:03:06 +00002174 ValueDecl* FoundVD = FieldME->getMemberDecl();
2175
Richard Trieuef64e942013-10-25 00:56:00 +00002176 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002177 return;
2178
Richard Trieuef64e942013-10-25 00:56:00 +00002179 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002180
Richard Trieuef64e942013-10-25 00:56:00 +00002181 // Prevent double warnings on use of unbounded references.
2182 if (IsReference != CheckReferenceOnly)
2183 return;
2184
2185 unsigned diag = IsReference
2186 ? diag::warn_reference_field_is_uninit
2187 : diag::warn_field_is_uninit;
2188 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2189 if (Constructor)
2190 S.Diag(Constructor->getLocation(),
2191 diag::note_uninit_in_this_constructor)
2192 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2193
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002194 }
2195
2196 void HandleValue(Expr *E) {
2197 E = E->IgnoreParens();
2198
2199 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002200 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002201 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002202 }
2203
2204 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2205 HandleValue(CO->getTrueExpr());
2206 HandleValue(CO->getFalseExpr());
2207 return;
2208 }
2209
2210 if (BinaryConditionalOperator *BCO =
2211 dyn_cast<BinaryConditionalOperator>(E)) {
2212 HandleValue(BCO->getCommon());
2213 HandleValue(BCO->getFalseExpr());
2214 return;
2215 }
2216
2217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2218 switch (BO->getOpcode()) {
2219 default:
2220 return;
2221 case(BO_PtrMemD):
2222 case(BO_PtrMemI):
2223 HandleValue(BO->getLHS());
2224 return;
2225 case(BO_Comma):
2226 HandleValue(BO->getRHS());
2227 return;
2228 }
2229 }
2230 }
2231
Richard Trieu1bc22c12013-09-13 03:20:53 +00002232 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002233 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002234 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002235
2236 Inherited::VisitMemberExpr(ME);
2237 }
2238
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002239 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2240 if (E->getCastKind() == CK_LValueToRValue)
2241 HandleValue(E->getSubExpr());
2242
2243 Inherited::VisitImplicitCastExpr(E);
2244 }
2245
Richard Trieu1bc22c12013-09-13 03:20:53 +00002246 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002247 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002248 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2249 if (ICE->getCastKind() == CK_NoOp)
2250 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002251 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002252
2253 Inherited::VisitCXXConstructExpr(E);
2254 }
2255
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002256 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2257 Expr *Callee = E->getCallee();
2258 if (isa<MemberExpr>(Callee))
2259 HandleValue(Callee);
2260
2261 Inherited::VisitCXXMemberCallExpr(E);
2262 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002263
2264 void VisitBinaryOperator(BinaryOperator *E) {
2265 // If a field assignment is detected, remove the field from the
2266 // uninitiailized field set.
2267 if (E->getOpcode() == BO_Assign)
2268 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2269 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002270 if (!FD->getType()->isReferenceType())
2271 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002272
2273 Inherited::VisitBinaryOperator(E);
2274 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002275 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002276 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002277 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2278 const CXXConstructorDecl *Constructor) {
2279 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002280 return;
2281
Richard Trieuef64e942013-10-25 00:56:00 +00002282 if (!E)
2283 return;
2284
2285 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2286 E = Default->getExpr();
2287 if (!E)
2288 return;
2289 // In class initializers will point to the constructor.
2290 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2291 } else {
2292 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2293 }
2294 }
2295
2296 // Diagnose value-uses of fields to initialize themselves, e.g.
2297 // foo(foo)
2298 // where foo is not also a parameter to the constructor.
2299 // Also diagnose across field uninitialized use such as
2300 // x(y), y(x)
2301 // TODO: implement -Wuninitialized and fold this into that framework.
2302 static void DiagnoseUninitializedFields(
2303 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2304
2305 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2306 Constructor->getLocation())
2307 == DiagnosticsEngine::Ignored) {
2308 return;
2309 }
2310
2311 if (Constructor->isInvalidDecl())
2312 return;
2313
2314 const CXXRecordDecl *RD = Constructor->getParent();
2315
2316 // Holds fields that are uninitialized.
2317 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2318
2319 // At the beginning, all fields are uninitialized.
2320 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2321 I != E; ++I) {
2322 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2323 UninitializedFields.insert(FD);
2324 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2325 UninitializedFields.insert(IFD->getAnonField());
2326 }
2327 }
2328
2329 for (CXXConstructorDecl::init_const_iterator FieldInit =
2330 Constructor->init_begin(),
2331 FieldInitEnd = Constructor->init_end();
2332 FieldInit != FieldInitEnd; ++FieldInit) {
2333
2334 Expr *InitExpr = (*FieldInit)->getInit();
2335
2336 CheckInitExprContainsUninitializedFields(
2337 SemaRef, InitExpr, UninitializedFields, Constructor);
2338
2339 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2340 UninitializedFields.erase(Field);
2341 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002342 }
2343} // namespace
2344
Richard Smith938f40b2011-06-11 17:19:42 +00002345/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00002346/// in-class initializer for a non-static C++ class member, and after
2347/// instantiating an in-class initializer in a class template. Such actions
2348/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00002349void
Richard Smith2b013182012-06-10 03:12:00 +00002350Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith938f40b2011-06-11 17:19:42 +00002351 Expr *InitExpr) {
2352 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002353 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2354 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002355
2356 if (!InitExpr) {
2357 FD->setInvalidDecl();
2358 FD->removeInClassInitializer();
2359 return;
2360 }
2361
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002362 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2363 FD->setInvalidDecl();
2364 FD->removeInClassInitializer();
2365 return;
2366 }
2367
Richard Smith938f40b2011-06-11 17:19:42 +00002368 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002369 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002370 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002371 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002372 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002373 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002374 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2375 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002376 if (Init.isInvalid()) {
2377 FD->setInvalidDecl();
2378 return;
2379 }
Richard Smith938f40b2011-06-11 17:19:42 +00002380 }
2381
Richard Smith945f8d32013-01-14 22:39:08 +00002382 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002383 // The initialization of each base and member constitutes a
2384 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002385 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002386 if (Init.isInvalid()) {
2387 FD->setInvalidDecl();
2388 return;
2389 }
2390
2391 InitExpr = Init.release();
2392
2393 FD->setInClassInitializer(InitExpr);
2394}
2395
Douglas Gregor15e77a22009-12-31 09:10:24 +00002396/// \brief Find the direct and/or virtual base specifiers that
2397/// correspond to the given base type, for use in base initialization
2398/// within a constructor.
2399static bool FindBaseInitializer(Sema &SemaRef,
2400 CXXRecordDecl *ClassDecl,
2401 QualType BaseType,
2402 const CXXBaseSpecifier *&DirectBaseSpec,
2403 const CXXBaseSpecifier *&VirtualBaseSpec) {
2404 // First, check for a direct base class.
2405 DirectBaseSpec = 0;
2406 for (CXXRecordDecl::base_class_const_iterator Base
2407 = ClassDecl->bases_begin();
2408 Base != ClassDecl->bases_end(); ++Base) {
2409 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2410 // We found a direct base of this type. That's what we're
2411 // initializing.
2412 DirectBaseSpec = &*Base;
2413 break;
2414 }
2415 }
2416
2417 // Check for a virtual base class.
2418 // FIXME: We might be able to short-circuit this if we know in advance that
2419 // there are no virtual bases.
2420 VirtualBaseSpec = 0;
2421 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2422 // We haven't found a base yet; search the class hierarchy for a
2423 // virtual base class.
2424 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2425 /*DetectVirtual=*/false);
2426 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2427 BaseType, Paths)) {
2428 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2429 Path != Paths.end(); ++Path) {
2430 if (Path->back().Base->isVirtual()) {
2431 VirtualBaseSpec = Path->back().Base;
2432 break;
2433 }
2434 }
2435 }
2436 }
2437
2438 return DirectBaseSpec || VirtualBaseSpec;
2439}
2440
Sebastian Redla74948d2011-09-24 17:48:25 +00002441/// \brief Handle a C++ member initializer using braced-init-list syntax.
2442MemInitResult
2443Sema::ActOnMemInitializer(Decl *ConstructorD,
2444 Scope *S,
2445 CXXScopeSpec &SS,
2446 IdentifierInfo *MemberOrBase,
2447 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002448 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002449 SourceLocation IdLoc,
2450 Expr *InitList,
2451 SourceLocation EllipsisLoc) {
2452 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002453 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002454 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002455}
2456
2457/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002458MemInitResult
John McCall48871652010-08-21 09:40:31 +00002459Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002460 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002461 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002462 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002463 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002464 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002465 SourceLocation IdLoc,
2466 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002467 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002468 SourceLocation RParenLoc,
2469 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002470 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002471 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002472 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002473 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002474}
2475
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002476namespace {
2477
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002478// Callback to only accept typo corrections that can be a valid C++ member
2479// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002480class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002481public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002482 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2483 : ClassDecl(ClassDecl) {}
2484
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002485 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002486 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2487 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2488 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002489 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002490 }
2491 return false;
2492 }
2493
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002494private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002495 CXXRecordDecl *ClassDecl;
2496};
2497
2498}
2499
Sebastian Redla74948d2011-09-24 17:48:25 +00002500/// \brief Handle a C++ member initializer.
2501MemInitResult
2502Sema::BuildMemInitializer(Decl *ConstructorD,
2503 Scope *S,
2504 CXXScopeSpec &SS,
2505 IdentifierInfo *MemberOrBase,
2506 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002507 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002508 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002509 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002510 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002511 if (!ConstructorD)
2512 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002514 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002515
2516 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002517 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002518 if (!Constructor) {
2519 // The user wrote a constructor initializer on a function that is
2520 // not a C++ constructor. Ignore the error for now, because we may
2521 // have more member initializers coming; we'll diagnose it just
2522 // once in ActOnMemInitializers.
2523 return true;
2524 }
2525
2526 CXXRecordDecl *ClassDecl = Constructor->getParent();
2527
2528 // C++ [class.base.init]p2:
2529 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002530 // constructor's class and, if not found in that scope, are looked
2531 // up in the scope containing the constructor's definition.
2532 // [Note: if the constructor's class contains a member with the
2533 // same name as a direct or virtual base class of the class, a
2534 // mem-initializer-id naming the member or base class and composed
2535 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002536 // mem-initializer-id for the hidden base class may be specified
2537 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002538 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002539 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002540 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002541 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002542 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002543 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002544 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2545 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002546 if (EllipsisLoc.isValid())
2547 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002548 << MemberOrBase
2549 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002550
Sebastian Redla9351792012-02-11 23:51:47 +00002551 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002552 }
Francois Pichetd583da02010-12-04 09:14:42 +00002553 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002554 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002555 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002556 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002557 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002558
2559 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002560 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002561 } else if (DS.getTypeSpecType() == TST_decltype) {
2562 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002563 } else {
2564 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2565 LookupParsedName(R, S, &SS);
2566
2567 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2568 if (!TyD) {
2569 if (R.isAmbiguous()) return true;
2570
John McCallda6841b2010-04-09 19:01:14 +00002571 // We don't want access-control diagnostics here.
2572 R.suppressDiagnostics();
2573
Douglas Gregora3b624a2010-01-19 06:46:48 +00002574 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2575 bool NotUnknownSpecialization = false;
2576 DeclContext *DC = computeDeclContext(SS, false);
2577 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2578 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2579
2580 if (!NotUnknownSpecialization) {
2581 // When the scope specifier can refer to a member of an unknown
2582 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002583 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2584 SS.getWithLocInContext(Context),
2585 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002586 if (BaseType.isNull())
2587 return true;
2588
Douglas Gregora3b624a2010-01-19 06:46:48 +00002589 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002590 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002591 }
2592 }
2593
Douglas Gregor15e77a22009-12-31 09:10:24 +00002594 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002595 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002596 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002597 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002598 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002599 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002600 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002601 // We have found a non-static data member with a similar
2602 // name to what was typed; complain and initialize that
2603 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002604 diagnoseTypo(Corr,
2605 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2606 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002607 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002608 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002609 const CXXBaseSpecifier *DirectBaseSpec;
2610 const CXXBaseSpecifier *VirtualBaseSpec;
2611 if (FindBaseInitializer(*this, ClassDecl,
2612 Context.getTypeDeclType(Type),
2613 DirectBaseSpec, VirtualBaseSpec)) {
2614 // We have found a direct or virtual base class with a
2615 // similar name to what was typed; complain and initialize
2616 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002617 diagnoseTypo(Corr,
2618 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2619 << MemberOrBase << false,
2620 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002621
Richard Smithf9b15102013-08-17 00:46:16 +00002622 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2623 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002624 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002625 diag::note_base_class_specified_here)
2626 << BaseSpec->getType()
2627 << BaseSpec->getSourceRange();
2628
Douglas Gregor15e77a22009-12-31 09:10:24 +00002629 TyD = Type;
2630 }
2631 }
2632 }
2633
Douglas Gregora3b624a2010-01-19 06:46:48 +00002634 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002635 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002636 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002637 return true;
2638 }
John McCallb5a0d312009-12-21 10:41:20 +00002639 }
2640
Douglas Gregora3b624a2010-01-19 06:46:48 +00002641 if (BaseType.isNull()) {
2642 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002643 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002644 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002645 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2646 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002647 }
2648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
John McCallbcd03502009-12-07 02:54:59 +00002650 if (!TInfo)
2651 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002652
Sebastian Redla9351792012-02-11 23:51:47 +00002653 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002654}
2655
Chandler Carruth599deef2011-09-03 01:14:15 +00002656/// Checks a member initializer expression for cases where reference (or
2657/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002658static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2659 Expr *Init,
2660 SourceLocation IdLoc) {
2661 QualType MemberTy = Member->getType();
2662
2663 // We only handle pointers and references currently.
2664 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2665 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2666 return;
2667
2668 const bool IsPointer = MemberTy->isPointerType();
2669 if (IsPointer) {
2670 if (const UnaryOperator *Op
2671 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2672 // The only case we're worried about with pointers requires taking the
2673 // address.
2674 if (Op->getOpcode() != UO_AddrOf)
2675 return;
2676
2677 Init = Op->getSubExpr();
2678 } else {
2679 // We only handle address-of expression initializers for pointers.
2680 return;
2681 }
2682 }
2683
Richard Smithe3b28bc2013-06-12 21:51:50 +00002684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002685 // We only warn when referring to a non-reference parameter declaration.
2686 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2687 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002688 return;
2689
2690 S.Diag(Init->getExprLoc(),
2691 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2692 : diag::warn_bind_ref_member_to_parameter)
2693 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002694 } else {
2695 // Other initializers are fine.
2696 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002697 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002698
2699 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2700 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002701}
2702
John McCallfaf5fb42010-08-26 23:41:50 +00002703MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002704Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002705 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002706 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2707 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2708 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002709 "Member must be a FieldDecl or IndirectFieldDecl");
2710
Sebastian Redla9351792012-02-11 23:51:47 +00002711 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002712 return true;
2713
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002714 if (Member->isInvalidDecl())
2715 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002716
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002717 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002718 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002719 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002720 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002721 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002722 } else {
2723 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002724 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002725 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002726
Sebastian Redla9351792012-02-11 23:51:47 +00002727 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002728
Sebastian Redla9351792012-02-11 23:51:47 +00002729 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002730 // Can't check initialization for a member of dependent type or when
2731 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002732 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002733 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002734 bool InitList = false;
2735 if (isa<InitListExpr>(Init)) {
2736 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002737 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002738 }
2739
Chandler Carruthd44c3102010-12-06 09:23:57 +00002740 // Initialize the member.
2741 InitializedEntity MemberEntity =
2742 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2743 : InitializedEntity::InitializeMember(IndirectMember, 0);
2744 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002745 InitList ? InitializationKind::CreateDirectList(IdLoc)
2746 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2747 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002748
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002749 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2750 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002751 if (MemberInit.isInvalid())
2752 return true;
2753
Richard Smith736a9472013-06-12 20:42:33 +00002754 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2755
Richard Smith945f8d32013-01-14 22:39:08 +00002756 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002757 // The initialization of each base and member constitutes a
2758 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002759 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002760 if (MemberInit.isInvalid())
2761 return true;
2762
Richard Smithd59b8322012-12-19 01:39:02 +00002763 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002764 }
2765
Chandler Carruthd44c3102010-12-06 09:23:57 +00002766 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002767 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2768 InitRange.getBegin(), Init,
2769 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002770 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002771 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2772 InitRange.getBegin(), Init,
2773 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002774 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002775}
2776
John McCallfaf5fb42010-08-26 23:41:50 +00002777MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002778Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002779 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002780 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002781 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002782 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002783 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002784 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002785
Sebastian Redl0501c632012-02-12 16:37:36 +00002786 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002787 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002788 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2789 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002790 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002791 }
2792
Sebastian Redla9351792012-02-11 23:51:47 +00002793 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002794 // Initialize the object.
2795 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2796 QualType(ClassDecl->getTypeForDecl(), 0));
2797 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002798 InitList ? InitializationKind::CreateDirectList(NameLoc)
2799 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2800 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002801 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002802 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002804 if (DelegationInit.isInvalid())
2805 return true;
2806
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002807 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2808 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002809
Richard Smith945f8d32013-01-14 22:39:08 +00002810 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002811 // The initialization of each base and member constitutes a
2812 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002813 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2814 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002815 if (DelegationInit.isInvalid())
2816 return true;
2817
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002818 // If we are in a dependent context, template instantiation will
2819 // perform this type-checking again. Just save the arguments that we
2820 // received in a ParenListExpr.
2821 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2822 // of the information that we have about the base
2823 // initializer. However, deconstructing the ASTs is a dicey process,
2824 // and this approach is far more likely to get the corner cases right.
2825 if (CurContext->isDependentContext())
2826 DelegationInit = Owned(Init);
2827
Sebastian Redla9351792012-02-11 23:51:47 +00002828 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002829 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002830 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002831}
2832
2833MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002834Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002835 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002836 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002837 SourceLocation BaseLoc
2838 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002839
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002840 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2841 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2842 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2843
2844 // C++ [class.base.init]p2:
2845 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002846 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002847 // of that class, the mem-initializer is ill-formed. A
2848 // mem-initializer-list can initialize a base class using any
2849 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002850 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002851
Sebastian Redla9351792012-02-11 23:51:47 +00002852 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002853 if (EllipsisLoc.isValid()) {
2854 // This is a pack expansion.
2855 if (!BaseType->containsUnexpandedParameterPack()) {
2856 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002857 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002858
Douglas Gregor44e7df62011-01-04 00:32:56 +00002859 EllipsisLoc = SourceLocation();
2860 }
2861 } else {
2862 // Check for any unexpanded parameter packs.
2863 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2864 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002865
Sebastian Redla9351792012-02-11 23:51:47 +00002866 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002867 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002868 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002869
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002870 // Check for direct and virtual base classes.
2871 const CXXBaseSpecifier *DirectBaseSpec = 0;
2872 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2873 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002874 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2875 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002876 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002877
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002878 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2879 VirtualBaseSpec);
2880
2881 // C++ [base.class.init]p2:
2882 // Unless the mem-initializer-id names a nonstatic data member of the
2883 // constructor's class or a direct or virtual base of that class, the
2884 // mem-initializer is ill-formed.
2885 if (!DirectBaseSpec && !VirtualBaseSpec) {
2886 // If the class has any dependent bases, then it's possible that
2887 // one of those types will resolve to the same type as
2888 // BaseType. Therefore, just treat this as a dependent base
2889 // class initialization. FIXME: Should we try to check the
2890 // initialization anyway? It seems odd.
2891 if (ClassDecl->hasAnyDependentBases())
2892 Dependent = true;
2893 else
2894 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2895 << BaseType << Context.getTypeDeclType(ClassDecl)
2896 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2897 }
2898 }
2899
2900 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002901 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002902
Sebastian Redla74948d2011-09-24 17:48:25 +00002903 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2904 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002905 InitRange.getBegin(), Init,
2906 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002907 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002908
2909 // C++ [base.class.init]p2:
2910 // If a mem-initializer-id is ambiguous because it designates both
2911 // a direct non-virtual base class and an inherited virtual base
2912 // class, the mem-initializer is ill-formed.
2913 if (DirectBaseSpec && VirtualBaseSpec)
2914 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002915 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002916
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002917 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002918 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002919 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002920
2921 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002922 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002923 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002924 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002925 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002926 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002927 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002928
2929 InitializedEntity BaseEntity =
2930 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2931 InitializationKind Kind =
2932 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2933 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2934 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002935 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2936 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002937 if (BaseInit.isInvalid())
2938 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002939
Richard Smith945f8d32013-01-14 22:39:08 +00002940 // C++11 [class.base.init]p7:
2941 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002942 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002943 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002944 if (BaseInit.isInvalid())
2945 return true;
2946
2947 // If we are in a dependent context, template instantiation will
2948 // perform this type-checking again. Just save the arguments that we
2949 // received in a ParenListExpr.
2950 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2951 // of the information that we have about the base
2952 // initializer. However, deconstructing the ASTs is a dicey process,
2953 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002954 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002955 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002956
Alexis Hunt1d792652011-01-08 20:30:50 +00002957 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002958 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002959 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002960 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002961 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002962}
2963
Sebastian Redl22653ba2011-08-30 19:58:05 +00002964// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002965static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2966 if (T.isNull()) T = E->getType();
2967 QualType TargetType = SemaRef.BuildReferenceType(
2968 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002969 SourceLocation ExprLoc = E->getLocStart();
2970 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2971 TargetType, ExprLoc);
2972
2973 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2974 SourceRange(ExprLoc, ExprLoc),
2975 E->getSourceRange()).take();
2976}
2977
Anders Carlsson1b00e242010-04-23 03:10:23 +00002978/// ImplicitInitializerKind - How an implicit base or member initializer should
2979/// initialize its base or member.
2980enum ImplicitInitializerKind {
2981 IIK_Default,
2982 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002983 IIK_Move,
2984 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002985};
2986
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002987static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002988BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002989 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002990 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002991 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002992 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002993 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002994 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2995 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002996
John McCalldadc5752010-08-24 06:29:42 +00002997 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002998
2999 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003000 case IIK_Inherit: {
3001 const CXXRecordDecl *Inherited =
3002 Constructor->getInheritedConstructor()->getParent();
3003 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3004 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3005 // C++11 [class.inhctor]p8:
3006 // Each expression in the expression-list is of the form
3007 // static_cast<T&&>(p), where p is the name of the corresponding
3008 // constructor parameter and T is the declared type of p.
3009 SmallVector<Expr*, 16> Args;
3010 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3011 ParmVarDecl *PD = Constructor->getParamDecl(I);
3012 ExprResult ArgExpr =
3013 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3014 VK_LValue, SourceLocation());
3015 if (ArgExpr.isInvalid())
3016 return true;
3017 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3018 }
3019
3020 InitializationKind InitKind = InitializationKind::CreateDirect(
3021 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003022 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003023 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3024 break;
3025 }
3026 }
3027 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003028 case IIK_Default: {
3029 InitializationKind InitKind
3030 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003031 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3032 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003033 break;
3034 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003035
Sebastian Redl22653ba2011-08-30 19:58:05 +00003036 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003037 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003038 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003039 ParmVarDecl *Param = Constructor->getParamDecl(0);
3040 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003041
Anders Carlsson1b00e242010-04-23 03:10:23 +00003042 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003043 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003044 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003045 Constructor->getLocation(), ParamType,
3046 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003047
Eli Friedmanfa0df832012-02-02 03:46:19 +00003048 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3049
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003050 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003051 QualType ArgTy =
3052 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3053 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003054
Sebastian Redl22653ba2011-08-30 19:58:05 +00003055 if (Moving) {
3056 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3057 }
3058
John McCallcf142162010-08-07 06:22:56 +00003059 CXXCastPath BasePath;
3060 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003061 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3062 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003063 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003064 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003065
Anders Carlsson1b00e242010-04-23 03:10:23 +00003066 InitializationKind InitKind
3067 = InitializationKind::CreateDirect(Constructor->getLocation(),
3068 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003069 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3070 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003071 break;
3072 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003073 }
John McCallb268a282010-08-23 23:25:46 +00003074
Douglas Gregora40433a2010-12-07 00:41:46 +00003075 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003076 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003077 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003078
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003079 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003080 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003081 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3082 SourceLocation()),
3083 BaseSpec->isVirtual(),
3084 SourceLocation(),
3085 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003086 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003087 SourceLocation());
3088
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003089 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003090}
3091
Sebastian Redl22653ba2011-08-30 19:58:05 +00003092static bool RefersToRValueRef(Expr *MemRef) {
3093 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3094 return Referenced->getType()->isRValueReferenceType();
3095}
3096
Anders Carlsson3c1db572010-04-23 02:15:47 +00003097static bool
3098BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003099 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003100 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003101 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003102 if (Field->isInvalidDecl())
3103 return true;
3104
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003105 SourceLocation Loc = Constructor->getLocation();
3106
Sebastian Redl22653ba2011-08-30 19:58:05 +00003107 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3108 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003109 ParmVarDecl *Param = Constructor->getParamDecl(0);
3110 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003111
3112 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003113 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3114 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003115
Anders Carlsson423f5d82010-04-23 16:04:08 +00003116 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003117 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003118 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003119 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003120
Eli Friedmanfa0df832012-02-02 03:46:19 +00003121 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3122
Sebastian Redl22653ba2011-08-30 19:58:05 +00003123 if (Moving) {
3124 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3125 }
3126
Douglas Gregor94f9a482010-05-05 05:51:00 +00003127 // Build a reference to this field within the parameter.
3128 CXXScopeSpec SS;
3129 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3130 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003131 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3132 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003133 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003134 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003135 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003136 ParamType, Loc,
3137 /*IsArrow=*/false,
3138 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003139 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003140 /*FirstQualifierInScope=*/0,
3141 MemberLookup,
3142 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003144 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003145
3146 // C++11 [class.copy]p15:
3147 // - if a member m has rvalue reference type T&&, it is direct-initialized
3148 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003149 if (RefersToRValueRef(CtorArg.get())) {
3150 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003151 }
3152
Douglas Gregor94f9a482010-05-05 05:51:00 +00003153 // When the field we are copying is an array, create index variables for
3154 // each dimension of the array. We use these index variables to subscript
3155 // the source array, and other clients (e.g., CodeGen) will perform the
3156 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003157 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003158 QualType BaseType = Field->getType();
3159 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003160 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003161 while (const ConstantArrayType *Array
3162 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003163 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003164 // Create the iteration variable for this array index.
3165 IdentifierInfo *IterationVarName = 0;
3166 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003167 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003168 llvm::raw_svector_ostream OS(Str);
3169 OS << "__i" << IndexVariables.size();
3170 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3171 }
3172 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003173 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003174 IterationVarName, SizeType,
3175 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003176 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003177 IndexVariables.push_back(IterationVar);
3178
3179 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003180 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003181 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003182 assert(!IterationVarRef.isInvalid() &&
3183 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003184 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3185 assert(!IterationVarRef.isInvalid() &&
3186 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003187
Douglas Gregor94f9a482010-05-05 05:51:00 +00003188 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003189 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003190 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003191 Loc);
3192 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003193 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003194
Douglas Gregor94f9a482010-05-05 05:51:00 +00003195 BaseType = Array->getElementType();
3196 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003197
3198 // The array subscript expression is an lvalue, which is wrong for moving.
3199 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003200 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003201
Douglas Gregor94f9a482010-05-05 05:51:00 +00003202 // Construct the entity that we will be initializing. For an array, this
3203 // will be first element in the array, which may require several levels
3204 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003205 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003206 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003207 if (Indirect)
3208 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3209 else
3210 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003211 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3212 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3213 0,
3214 Entities.back()));
3215
3216 // Direct-initialize to use the copy constructor.
3217 InitializationKind InitKind =
3218 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3219
Sebastian Redle9c4e842011-09-04 18:14:28 +00003220 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003221 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003222
John McCalldadc5752010-08-24 06:29:42 +00003223 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003224 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003225 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003226 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003227 if (MemberInit.isInvalid())
3228 return true;
3229
Douglas Gregor493627b2011-08-10 15:22:55 +00003230 if (Indirect) {
3231 assert(IndexVariables.size() == 0 &&
3232 "Indirect field improperly initialized");
3233 CXXMemberInit
3234 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3235 Loc, Loc,
3236 MemberInit.takeAs<Expr>(),
3237 Loc);
3238 } else
3239 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3240 Loc, MemberInit.takeAs<Expr>(),
3241 Loc,
3242 IndexVariables.data(),
3243 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003244 return false;
3245 }
3246
Richard Smithc2bc61b2013-03-18 21:12:30 +00003247 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3248 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003249
Anders Carlsson3c1db572010-04-23 02:15:47 +00003250 QualType FieldBaseElementType =
3251 SemaRef.Context.getBaseElementType(Field->getType());
3252
Anders Carlsson3c1db572010-04-23 02:15:47 +00003253 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003254 InitializedEntity InitEntity
3255 = Indirect? InitializedEntity::InitializeMember(Indirect)
3256 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003257 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003258 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003259
3260 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3261 ExprResult MemberInit =
3262 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003263
Douglas Gregora40433a2010-12-07 00:41:46 +00003264 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003265 if (MemberInit.isInvalid())
3266 return true;
3267
Douglas Gregor493627b2011-08-10 15:22:55 +00003268 if (Indirect)
3269 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3270 Indirect, Loc,
3271 Loc,
3272 MemberInit.get(),
3273 Loc);
3274 else
3275 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3276 Field, Loc, Loc,
3277 MemberInit.get(),
3278 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003279 return false;
3280 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003281
Alexis Hunt8b455182011-05-17 00:19:05 +00003282 if (!Field->getParent()->isUnion()) {
3283 if (FieldBaseElementType->isReferenceType()) {
3284 SemaRef.Diag(Constructor->getLocation(),
3285 diag::err_uninitialized_member_in_ctor)
3286 << (int)Constructor->isImplicit()
3287 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3288 << 0 << Field->getDeclName();
3289 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3290 return true;
3291 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003292
Alexis Hunt8b455182011-05-17 00:19:05 +00003293 if (FieldBaseElementType.isConstQualified()) {
3294 SemaRef.Diag(Constructor->getLocation(),
3295 diag::err_uninitialized_member_in_ctor)
3296 << (int)Constructor->isImplicit()
3297 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3298 << 1 << Field->getDeclName();
3299 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3300 return true;
3301 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003302 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003303
David Blaikiebbafb8a2012-03-11 07:00:24 +00003304 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003305 FieldBaseElementType->isObjCRetainableType() &&
3306 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3307 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003308 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003309 // Default-initialize Objective-C pointers to NULL.
3310 CXXMemberInit
3311 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3312 Loc, Loc,
3313 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3314 Loc);
3315 return false;
3316 }
3317
Anders Carlsson3c1db572010-04-23 02:15:47 +00003318 // Nothing to initialize.
3319 CXXMemberInit = 0;
3320 return false;
3321}
John McCallbc83b3f2010-05-20 23:23:51 +00003322
3323namespace {
3324struct BaseAndFieldInfo {
3325 Sema &S;
3326 CXXConstructorDecl *Ctor;
3327 bool AnyErrorsInInits;
3328 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003329 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003331 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003332
3333 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3334 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003335 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3336 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003337 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003338 else if (Generated && Ctor->isMoveConstructor())
3339 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003340 else if (Ctor->getInheritedConstructor())
3341 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003342 else
3343 IIK = IIK_Default;
3344 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003345
3346 bool isImplicitCopyOrMove() const {
3347 switch (IIK) {
3348 case IIK_Copy:
3349 case IIK_Move:
3350 return true;
3351
3352 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003353 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003354 return false;
3355 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003356
3357 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003358 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003359
3360 bool addFieldInitializer(CXXCtorInitializer *Init) {
3361 AllToInit.push_back(Init);
3362
3363 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003364 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003365 S.UnusedPrivateFields.remove(Init->getAnyMember());
3366
3367 return false;
3368 }
John McCallbc83b3f2010-05-20 23:23:51 +00003369
Richard Smithab44d5b2013-12-10 08:25:00 +00003370 bool isInactiveUnionMember(FieldDecl *Field) {
3371 RecordDecl *Record = Field->getParent();
3372 if (!Record->isUnion())
3373 return false;
3374
Richard Smith8d183852013-12-10 20:56:03 +00003375 if (FieldDecl *Active =
3376 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003377 return Active != Field->getCanonicalDecl();
3378
3379 // In an implicit copy or move constructor, ignore any in-class initializer.
3380 if (isImplicitCopyOrMove())
3381 return true;
3382
3383 // If there's no explicit initialization, the field is active only if it
3384 // has an in-class initializer...
3385 if (Field->hasInClassInitializer())
3386 return false;
3387 // ... or it's an anonymous struct or union whose class has an in-class
3388 // initializer.
3389 if (!Field->isAnonymousStructOrUnion())
3390 return true;
3391 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3392 return !FieldRD->hasInClassInitializer();
3393 }
3394
3395 /// \brief Determine whether the given field is, or is within, a union member
3396 /// that is inactive (because there was an initializer given for a different
3397 /// member of the union, or because the union was not initialized at all).
3398 bool isWithinInactiveUnionMember(FieldDecl *Field,
3399 IndirectFieldDecl *Indirect) {
3400 if (!Indirect)
3401 return isInactiveUnionMember(Field);
3402
3403 for (IndirectFieldDecl::chain_iterator C = Indirect->chain_begin(),
3404 CEnd = Indirect->chain_end();
3405 C != CEnd; ++C) {
3406 FieldDecl *Field = dyn_cast<FieldDecl>(*C);
3407 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003408 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003409 }
3410 return false;
3411 }
3412};
Richard Smithc94ec842011-09-19 13:34:43 +00003413}
3414
Douglas Gregor10f939c2011-11-02 23:04:16 +00003415/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3416/// array type.
3417static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3418 if (T->isIncompleteArrayType())
3419 return true;
3420
3421 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3422 if (!ArrayT->getSize())
3423 return true;
3424
3425 T = ArrayT->getElementType();
3426 }
3427
3428 return false;
3429}
3430
Richard Smith938f40b2011-06-11 17:19:42 +00003431static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003432 FieldDecl *Field,
3433 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003434 if (Field->isInvalidDecl())
3435 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003436
Chandler Carruth139e9622010-06-30 02:59:29 +00003437 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003438 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3439 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003440
Richard Smithab44d5b2013-12-10 08:25:00 +00003441 // C++11 [class.base.init]p8:
3442 // if the entity is a non-static data member that has a
3443 // brace-or-equal-initializer and either
3444 // -- the constructor's class is a union and no other variant member of that
3445 // union is designated by a mem-initializer-id or
3446 // -- the constructor's class is not a union, and, if the entity is a member
3447 // of an anonymous union, no other member of that union is designated by
3448 // a mem-initializer-id,
3449 // the entity is initialized as specified in [dcl.init].
3450 //
3451 // We also apply the same rules to handle anonymous structs within anonymous
3452 // unions.
3453 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3454 return false;
3455
Douglas Gregor7db3e952011-11-28 20:03:15 +00003456 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003457 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3458 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003459 CXXCtorInitializer *Init;
3460 if (Indirect)
3461 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3462 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003463 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003464 SourceLocation());
3465 else
3466 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3467 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003468 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003469 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003470 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003471 }
3472
Douglas Gregor10f939c2011-11-02 23:04:16 +00003473 // Don't initialize incomplete or zero-length arrays.
3474 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3475 return false;
3476
John McCallbc83b3f2010-05-20 23:23:51 +00003477 // Don't try to build an implicit initializer if there were semantic
3478 // errors in any of the initializers (and therefore we might be
3479 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003480 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003481 return false;
3482
Alexis Hunt1d792652011-01-08 20:30:50 +00003483 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003484 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3485 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003486 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003487
Richard Smith0a8cfc72012-08-07 21:30:42 +00003488 if (!Init)
3489 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003490
Richard Smith0a8cfc72012-08-07 21:30:42 +00003491 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003492}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003493
3494bool
3495Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3496 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003497 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003498 Constructor->setNumCtorInitializers(1);
3499 CXXCtorInitializer **initializer =
3500 new (Context) CXXCtorInitializer*[1];
3501 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3502 Constructor->setCtorInitializers(initializer);
3503
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003504 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003505 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003506 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3507 }
3508
Alexis Hunte2622992011-05-05 00:05:47 +00003509 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003510
Alexis Hunt61bc1732011-05-01 07:04:31 +00003511 return false;
3512}
Douglas Gregor493627b2011-08-10 15:22:55 +00003513
David Blaikie3fc2f912013-01-17 05:26:25 +00003514bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3515 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003516 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003517 // Just store the initializers as written, they will be checked during
3518 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003519 if (!Initializers.empty()) {
3520 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003521 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003522 new (Context) CXXCtorInitializer*[Initializers.size()];
3523 memcpy(baseOrMemberInitializers, Initializers.data(),
3524 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003525 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003526 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003527
3528 // Let template instantiation know whether we had errors.
3529 if (AnyErrors)
3530 Constructor->setInvalidDecl();
3531
Anders Carlssondb0a9652010-04-02 06:26:44 +00003532 return false;
3533 }
3534
John McCallbc83b3f2010-05-20 23:23:51 +00003535 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003536
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003537 // We need to build the initializer AST according to order of construction
3538 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003539 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003540 if (!ClassDecl)
3541 return true;
3542
Eli Friedman9cf6b592009-11-09 19:20:36 +00003543 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003544
David Blaikie3fc2f912013-01-17 05:26:25 +00003545 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003546 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003547
Anders Carlssondb0a9652010-04-02 06:26:44 +00003548 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003549 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003550 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003551 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003552
3553 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3554 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3555 CEnd = F->chain_end();
3556 C != CEnd; ++C) {
3557 FieldDecl *FD = dyn_cast<FieldDecl>(*C);
3558 if (FD && FD->getParent()->isUnion())
3559 Info.ActiveUnionMember.insert(std::make_pair(
3560 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3561 }
3562 } else if (FieldDecl *FD = Member->getMember()) {
3563 if (FD->getParent()->isUnion())
3564 Info.ActiveUnionMember.insert(std::make_pair(
3565 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3566 }
3567 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003568 }
3569
Anders Carlsson43c64af2010-04-21 19:52:01 +00003570 // Keep track of the direct virtual bases.
3571 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3572 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3573 E = ClassDecl->bases_end(); I != E; ++I) {
3574 if (I->isVirtual())
3575 DirectVBases.insert(I);
3576 }
3577
Anders Carlssondb0a9652010-04-02 06:26:44 +00003578 // Push virtual bases before others.
3579 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3580 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3581
Alexis Hunt1d792652011-01-08 20:30:50 +00003582 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003583 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003584 // [class.base.init]p7, per DR257:
3585 // A mem-initializer where the mem-initializer-id names a virtual base
3586 // class is ignored during execution of a constructor of any class that
3587 // is not the most derived class.
3588 if (ClassDecl->isAbstract()) {
3589 // FIXME: Provide a fixit to remove the base specifier. This requires
3590 // tracking the location of the associated comma for a base specifier.
3591 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3592 << VBase->getType() << ClassDecl;
3593 DiagnoseAbstractType(ClassDecl);
3594 }
3595
John McCallbc83b3f2010-05-20 23:23:51 +00003596 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003597 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3598 // [class.base.init]p8, per DR257:
3599 // If a given [...] base class is not named by a mem-initializer-id
3600 // [...] and the entity is not a virtual base class of an abstract
3601 // class, then [...] the entity is default-initialized.
Anders Carlsson43c64af2010-04-21 19:52:01 +00003602 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003603 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003604 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithbc46e432013-07-22 02:56:56 +00003605 VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003606 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003607 HadError = true;
3608 continue;
3609 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003610
John McCallbc83b3f2010-05-20 23:23:51 +00003611 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003612 }
3613 }
Mike Stump11289f42009-09-09 15:08:12 +00003614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003616 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3617 E = ClassDecl->bases_end(); Base != E; ++Base) {
3618 // Virtuals are in the virtual base list and already constructed.
3619 if (Base->isVirtual())
3620 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003621
Alexis Hunt1d792652011-01-08 20:30:50 +00003622 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003623 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3624 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003625 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003626 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003627 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003628 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003629 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003630 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003631 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003632 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003633
John McCallbc83b3f2010-05-20 23:23:51 +00003634 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003635 }
3636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
John McCallbc83b3f2010-05-20 23:23:51 +00003638 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00003639 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3640 MemEnd = ClassDecl->decls_end();
3641 Mem != MemEnd; ++Mem) {
3642 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003643 // C++ [class.bit]p2:
3644 // A declaration for a bit-field that omits the identifier declares an
3645 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3646 // initialized.
3647 if (F->isUnnamedBitfield())
3648 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003649
Sebastian Redl22653ba2011-08-30 19:58:05 +00003650 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003651 // handle anonymous struct/union fields based on their individual
3652 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003653 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003654 continue;
3655
3656 if (CollectFieldInitializer(*this, Info, F))
3657 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003658 continue;
3659 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003660
3661 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003662 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003663 continue;
3664
3665 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3666 if (F->getType()->isIncompleteArrayType()) {
3667 assert(ClassDecl->hasFlexibleArrayMember() &&
3668 "Incomplete array type is not valid");
3669 continue;
3670 }
3671
Douglas Gregor493627b2011-08-10 15:22:55 +00003672 // Initialize each field of an anonymous struct individually.
3673 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3674 HadError = true;
3675
3676 continue;
3677 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
David Blaikie3fc2f912013-01-17 05:26:25 +00003680 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003681 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003682 Constructor->setNumCtorInitializers(NumInitializers);
3683 CXXCtorInitializer **baseOrMemberInitializers =
3684 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003685 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003686 NumInitializers * sizeof(CXXCtorInitializer*));
3687 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003688
John McCalla6309952010-03-16 21:39:52 +00003689 // Constructors implicitly reference the base and member
3690 // destructors.
3691 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3692 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003693 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003694
3695 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003696}
3697
David Blaikieb61b8152013-01-17 08:49:22 +00003698static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003699 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003700 const RecordDecl *RD = RT->getDecl();
3701 if (RD->isAnonymousStructOrUnion()) {
3702 for (RecordDecl::field_iterator Field = RD->field_begin(),
3703 E = RD->field_end(); Field != E; ++Field)
3704 PopulateKeysForFields(*Field, IdealInits);
3705 return;
3706 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003707 }
David Blaikieb61b8152013-01-17 08:49:22 +00003708 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003709}
3710
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003711static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3712 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003713}
3714
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003715static const void *GetKeyForMember(ASTContext &Context,
3716 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003717 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003718 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003719
David Blaikieb61b8152013-01-17 08:49:22 +00003720 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003721}
3722
David Blaikie3fc2f912013-01-17 05:26:25 +00003723static void DiagnoseBaseOrMemInitializerOrder(
3724 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3725 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003726 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003727 return;
Mike Stump11289f42009-09-09 15:08:12 +00003728
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003729 // Don't check initializers order unless the warning is enabled at the
3730 // location of at least one initializer.
3731 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003732 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003733 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003734 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3735 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003736 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003737 ShouldCheckOrder = true;
3738 break;
3739 }
3740 }
3741 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003742 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003743
John McCallbb7b6582010-04-10 07:37:23 +00003744 // Build the list of bases and members in the order that they'll
3745 // actually be initialized. The explicit initializers should be in
3746 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003747 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003748
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003749 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3750
John McCallbb7b6582010-04-10 07:37:23 +00003751 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003752 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003753 ClassDecl->vbases_begin(),
3754 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003755 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003756
John McCallbb7b6582010-04-10 07:37:23 +00003757 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003758 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003759 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003760 if (Base->isVirtual())
3761 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003762 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003763 }
Mike Stump11289f42009-09-09 15:08:12 +00003764
John McCallbb7b6582010-04-10 07:37:23 +00003765 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003766 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003767 E = ClassDecl->field_end(); Field != E; ++Field) {
3768 if (Field->isUnnamedBitfield())
3769 continue;
3770
David Blaikieb61b8152013-01-17 08:49:22 +00003771 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003772 }
3773
John McCallbb7b6582010-04-10 07:37:23 +00003774 unsigned NumIdealInits = IdealInitKeys.size();
3775 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003776
Alexis Hunt1d792652011-01-08 20:30:50 +00003777 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003778 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003779 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003780 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003781
3782 // Scan forward to try to find this initializer in the idealized
3783 // initializers list.
3784 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3785 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003786 break;
John McCallbb7b6582010-04-10 07:37:23 +00003787
3788 // If we didn't find this initializer, it must be because we
3789 // scanned past it on a previous iteration. That can only
3790 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003791 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003792 Sema::SemaDiagnosticBuilder D =
3793 SemaRef.Diag(PrevInit->getSourceLocation(),
3794 diag::warn_initializer_out_of_order);
3795
Francois Pichetd583da02010-12-04 09:14:42 +00003796 if (PrevInit->isAnyMemberInitializer())
3797 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003798 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003799 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003800
Francois Pichetd583da02010-12-04 09:14:42 +00003801 if (Init->isAnyMemberInitializer())
3802 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003803 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003804 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003805
3806 // Move back to the initializer's location in the ideal list.
3807 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3808 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003809 break;
John McCallbb7b6582010-04-10 07:37:23 +00003810
3811 assert(IdealIndex != NumIdealInits &&
3812 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003813 }
John McCallbb7b6582010-04-10 07:37:23 +00003814
3815 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003816 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003817}
3818
John McCall23eebd92010-04-10 09:28:51 +00003819namespace {
3820bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003821 CXXCtorInitializer *Init,
3822 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003823 if (!PrevInit) {
3824 PrevInit = Init;
3825 return false;
3826 }
3827
Douglas Gregorea306a12013-03-25 23:28:23 +00003828 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003829 S.Diag(Init->getSourceLocation(),
3830 diag::err_multiple_mem_initialization)
3831 << Field->getDeclName()
3832 << Init->getSourceRange();
3833 else {
John McCall424cec92011-01-19 06:33:43 +00003834 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003835 assert(BaseClass && "neither field nor base");
3836 S.Diag(Init->getSourceLocation(),
3837 diag::err_multiple_base_initialization)
3838 << QualType(BaseClass, 0)
3839 << Init->getSourceRange();
3840 }
3841 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3842 << 0 << PrevInit->getSourceRange();
3843
3844 return true;
3845}
3846
Alexis Hunt1d792652011-01-08 20:30:50 +00003847typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003848typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3849
3850bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003851 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003852 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003853 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003854 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003855 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003856
3857 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003858 if (Parent->isUnion()) {
3859 UnionEntry &En = Unions[Parent];
3860 if (En.first && En.first != Child) {
3861 S.Diag(Init->getSourceLocation(),
3862 diag::err_multiple_mem_union_initialization)
3863 << Field->getDeclName()
3864 << Init->getSourceRange();
3865 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3866 << 0 << En.second->getSourceRange();
3867 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003868 }
3869 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003870 En.first = Child;
3871 En.second = Init;
3872 }
David Blaikie0f65d592011-11-17 06:01:57 +00003873 if (!Parent->isAnonymousStructOrUnion())
3874 return false;
John McCall23eebd92010-04-10 09:28:51 +00003875 }
3876
3877 Child = Parent;
3878 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003879 }
John McCall23eebd92010-04-10 09:28:51 +00003880
3881 return false;
3882}
3883}
3884
Anders Carlssone857b292010-04-02 03:37:03 +00003885/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003886void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003887 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003888 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003889 bool AnyErrors) {
3890 if (!ConstructorDecl)
3891 return;
3892
3893 AdjustDeclIfTemplate(ConstructorDecl);
3894
3895 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003896 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003897
3898 if (!Constructor) {
3899 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3900 return;
3901 }
3902
John McCall23eebd92010-04-10 09:28:51 +00003903 // Mapping for the duplicate initializers check.
3904 // For member initializers, this is keyed with a FieldDecl*.
3905 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003906 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003907
3908 // Mapping for the inconsistent anonymous-union initializers check.
3909 RedundantUnionMap MemberUnions;
3910
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003911 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003912 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003913 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003914
Abramo Bagnara341d7832010-05-26 18:09:23 +00003915 // Set the source order index.
3916 Init->setSourceOrder(i);
3917
Francois Pichetd583da02010-12-04 09:14:42 +00003918 if (Init->isAnyMemberInitializer()) {
3919 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003920 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3921 CheckRedundantUnionInit(*this, Init, MemberUnions))
3922 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003923 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003924 const void *Key =
3925 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003926 if (CheckRedundantInit(*this, Init, Members[Key]))
3927 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003928 } else {
3929 assert(Init->isDelegatingInitializer());
3930 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003931 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003932 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003933 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003934 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003935 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003936 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003937 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003938 // Return immediately as the initializer is set.
3939 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003940 }
Anders Carlssone857b292010-04-02 03:37:03 +00003941 }
3942
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003943 if (HadError)
3944 return;
3945
David Blaikie3fc2f912013-01-17 05:26:25 +00003946 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003947
David Blaikie3fc2f912013-01-17 05:26:25 +00003948 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003949
Richard Trieuef64e942013-10-25 00:56:00 +00003950 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003951}
3952
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003953void
John McCalla6309952010-03-16 21:39:52 +00003954Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3955 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003956 // Ignore dependent contexts. Also ignore unions, since their members never
3957 // have destructors implicitly called.
3958 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003959 return;
John McCall1064d7e2010-03-16 05:22:47 +00003960
3961 // FIXME: all the access-control diagnostics are positioned on the
3962 // field/base declaration. That's probably good; that said, the
3963 // user might reasonably want to know why the destructor is being
3964 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003965
Anders Carlssondee9a302009-11-17 04:44:12 +00003966 // Non-static data members.
3967 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3968 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003969 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003970 if (Field->isInvalidDecl())
3971 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003972
3973 // Don't destroy incomplete or zero-length arrays.
3974 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3975 continue;
3976
Anders Carlssondee9a302009-11-17 04:44:12 +00003977 QualType FieldType = Context.getBaseElementType(Field->getType());
3978
3979 const RecordType* RT = FieldType->getAs<RecordType>();
3980 if (!RT)
3981 continue;
3982
3983 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003984 if (FieldClassDecl->isInvalidDecl())
3985 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003986 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003987 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003988 // The destructor for an implicit anonymous union member is never invoked.
3989 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3990 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003991
Douglas Gregore71edda2010-07-01 22:47:18 +00003992 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003993 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003994 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003995 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003996 << Field->getDeclName()
3997 << FieldType);
3998
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003999 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004000 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004001 }
4002
John McCall1064d7e2010-03-16 05:22:47 +00004003 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4004
Anders Carlssondee9a302009-11-17 04:44:12 +00004005 // Bases.
4006 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4007 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00004008 // Bases are always records in a well-formed non-dependent class.
4009 const RecordType *RT = Base->getType()->getAs<RecordType>();
4010
4011 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00004012 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004013 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004014
John McCall1064d7e2010-03-16 05:22:47 +00004015 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004016 // If our base class is invalid, we probably can't get its dtor anyway.
4017 if (BaseClassDecl->isInvalidDecl())
4018 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004019 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004020 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004021
Douglas Gregore71edda2010-07-01 22:47:18 +00004022 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004023 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004024
4025 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004026 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004027 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00004028 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00004029 << Base->getSourceRange(),
4030 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004031
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004032 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004033 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004034 }
4035
4036 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004037 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4038 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00004039
4040 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00004041 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004042
4043 // Ignore direct virtual bases.
4044 if (DirectVirtualBases.count(RT))
4045 continue;
4046
John McCall1064d7e2010-03-16 05:22:47 +00004047 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004048 // If our base class is invalid, we probably can't get its dtor anyway.
4049 if (BaseClassDecl->isInvalidDecl())
4050 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004051 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004052 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004053
Douglas Gregore71edda2010-07-01 22:47:18 +00004054 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004055 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004056 if (CheckDestructorAccess(
4057 ClassDecl->getLocation(), Dtor,
4058 PDiag(diag::err_access_dtor_vbase)
4059 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4060 Context.getTypeDeclType(ClassDecl)) ==
4061 AR_accessible) {
4062 CheckDerivedToBaseConversion(
4063 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4064 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4065 SourceRange(), DeclarationName(), 0);
4066 }
John McCall1064d7e2010-03-16 05:22:47 +00004067
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004068 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004069 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004070 }
4071}
4072
John McCall48871652010-08-21 09:40:31 +00004073void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004074 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004075 return;
Mike Stump11289f42009-09-09 15:08:12 +00004076
Mike Stump11289f42009-09-09 15:08:12 +00004077 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004078 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004079 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004080 DiagnoseUninitializedFields(*this, Constructor);
4081 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004082}
4083
Mike Stump11289f42009-09-09 15:08:12 +00004084bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004085 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004086 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4087 unsigned DiagID;
4088 AbstractDiagSelID SelID;
4089
4090 public:
4091 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4092 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004093
4094 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004095 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004096 if (SelID == -1)
4097 S.Diag(Loc, DiagID) << T;
4098 else
4099 S.Diag(Loc, DiagID) << SelID << T;
4100 }
4101 } Diagnoser(DiagID, SelID);
4102
4103 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004104}
4105
Anders Carlssoneabf7702009-08-27 00:13:57 +00004106bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004107 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004108 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004109 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004110
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004111 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004112 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004113
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004114 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004115 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004116 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004117 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004118
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004119 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004120 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004121 }
Mike Stump11289f42009-09-09 15:08:12 +00004122
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004123 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004124 if (!RT)
4125 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004126
John McCall67da35c2010-02-04 22:26:26 +00004127 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004128
John McCall02db245d2010-08-18 09:41:07 +00004129 // We can't answer whether something is abstract until it has a
4130 // definition. If it's currently being defined, we'll walk back
4131 // over all the declarations when we have a full definition.
4132 const CXXRecordDecl *Def = RD->getDefinition();
4133 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004134 return false;
4135
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004136 if (!RD->isAbstract())
4137 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004138
Douglas Gregorae298422012-05-04 17:09:59 +00004139 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004140 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004141
John McCall02db245d2010-08-18 09:41:07 +00004142 return true;
4143}
4144
4145void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4146 // Check if we've already emitted the list of pure virtual functions
4147 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004148 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004149 return;
Mike Stump11289f42009-09-09 15:08:12 +00004150
Richard Smithbc46e432013-07-22 02:56:56 +00004151 // If the diagnostic is suppressed, don't emit the notes. We're only
4152 // going to emit them once, so try to attach them to a diagnostic we're
4153 // actually going to show.
4154 if (Diags.isLastDiagnosticIgnored())
4155 return;
4156
Douglas Gregor4165bd62010-03-23 23:47:56 +00004157 CXXFinalOverriderMap FinalOverriders;
4158 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004159
Anders Carlssona2f74f32010-06-03 01:00:02 +00004160 // Keep a set of seen pure methods so we won't diagnose the same method
4161 // more than once.
4162 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4163
Douglas Gregor4165bd62010-03-23 23:47:56 +00004164 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4165 MEnd = FinalOverriders.end();
4166 M != MEnd;
4167 ++M) {
4168 for (OverridingMethods::iterator SO = M->second.begin(),
4169 SOEnd = M->second.end();
4170 SO != SOEnd; ++SO) {
4171 // C++ [class.abstract]p4:
4172 // A class is abstract if it contains or inherits at least one
4173 // pure virtual function for which the final overrider is pure
4174 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004175
Douglas Gregor4165bd62010-03-23 23:47:56 +00004176 //
4177 if (SO->second.size() != 1)
4178 continue;
4179
4180 if (!SO->second.front().Method->isPure())
4181 continue;
4182
Anders Carlssona2f74f32010-06-03 01:00:02 +00004183 if (!SeenPureMethods.insert(SO->second.front().Method))
4184 continue;
4185
Douglas Gregor4165bd62010-03-23 23:47:56 +00004186 Diag(SO->second.front().Method->getLocation(),
4187 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004188 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004189 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004190 }
4191
4192 if (!PureVirtualClassDiagSet)
4193 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4194 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004195}
4196
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004197namespace {
John McCall02db245d2010-08-18 09:41:07 +00004198struct AbstractUsageInfo {
4199 Sema &S;
4200 CXXRecordDecl *Record;
4201 CanQualType AbstractType;
4202 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCall02db245d2010-08-18 09:41:07 +00004204 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4205 : S(S), Record(Record),
4206 AbstractType(S.Context.getCanonicalType(
4207 S.Context.getTypeDeclType(Record))),
4208 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004209
John McCall02db245d2010-08-18 09:41:07 +00004210 void DiagnoseAbstractType() {
4211 if (Invalid) return;
4212 S.DiagnoseAbstractType(Record);
4213 Invalid = true;
4214 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004215
John McCall02db245d2010-08-18 09:41:07 +00004216 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4217};
4218
4219struct CheckAbstractUsage {
4220 AbstractUsageInfo &Info;
4221 const NamedDecl *Ctx;
4222
4223 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4224 : Info(Info), Ctx(Ctx) {}
4225
4226 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4227 switch (TL.getTypeLocClass()) {
4228#define ABSTRACT_TYPELOC(CLASS, PARENT)
4229#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004230 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004231#include "clang/AST/TypeLocNodes.def"
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 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4236 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4237 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004238 if (!TL.getArg(I))
4239 continue;
4240
John McCall02db245d2010-08-18 09:41:07 +00004241 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4242 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004243 }
John McCall02db245d2010-08-18 09:41:07 +00004244 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004245
John McCall02db245d2010-08-18 09:41:07 +00004246 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4247 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John McCall02db245d2010-08-18 09:41:07 +00004250 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4251 // Visit the type parameters from a permissive context.
4252 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4253 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4254 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4255 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4256 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4257 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004258 }
John McCall02db245d2010-08-18 09:41:07 +00004259 }
Mike Stump11289f42009-09-09 15:08:12 +00004260
John McCall02db245d2010-08-18 09:41:07 +00004261 // Visit pointee types from a permissive context.
4262#define CheckPolymorphic(Type) \
4263 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4264 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4265 }
4266 CheckPolymorphic(PointerTypeLoc)
4267 CheckPolymorphic(ReferenceTypeLoc)
4268 CheckPolymorphic(MemberPointerTypeLoc)
4269 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004270 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004271
John McCall02db245d2010-08-18 09:41:07 +00004272 /// Handle all the types we haven't given a more specific
4273 /// implementation for above.
4274 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4275 // Every other kind of type that we haven't called out already
4276 // that has an inner type is either (1) sugar or (2) contains that
4277 // inner type in some way as a subobject.
4278 if (TypeLoc Next = TL.getNextTypeLoc())
4279 return Visit(Next, Sel);
4280
4281 // If there's no inner type and we're in a permissive context,
4282 // don't diagnose.
4283 if (Sel == Sema::AbstractNone) return;
4284
4285 // Check whether the type matches the abstract type.
4286 QualType T = TL.getType();
4287 if (T->isArrayType()) {
4288 Sel = Sema::AbstractArrayType;
4289 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004290 }
John McCall02db245d2010-08-18 09:41:07 +00004291 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4292 if (CT != Info.AbstractType) return;
4293
4294 // It matched; do some magic.
4295 if (Sel == Sema::AbstractArrayType) {
4296 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4297 << T << TL.getSourceRange();
4298 } else {
4299 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4300 << Sel << T << TL.getSourceRange();
4301 }
4302 Info.DiagnoseAbstractType();
4303 }
4304};
4305
4306void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4307 Sema::AbstractDiagSelID Sel) {
4308 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4309}
4310
4311}
4312
4313/// Check for invalid uses of an abstract type in a method declaration.
4314static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4315 CXXMethodDecl *MD) {
4316 // No need to do the check on definitions, which require that
4317 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004318 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004319 return;
4320
4321 // For safety's sake, just ignore it if we don't have type source
4322 // information. This should never happen for non-implicit methods,
4323 // but...
4324 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4325 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4326}
4327
4328/// Check for invalid uses of an abstract type within a class definition.
4329static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4330 CXXRecordDecl *RD) {
4331 for (CXXRecordDecl::decl_iterator
4332 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4333 Decl *D = *I;
4334 if (D->isImplicit()) continue;
4335
4336 // Methods and method templates.
4337 if (isa<CXXMethodDecl>(D)) {
4338 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4339 } else if (isa<FunctionTemplateDecl>(D)) {
4340 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4341 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4342
4343 // Fields and static variables.
4344 } else if (isa<FieldDecl>(D)) {
4345 FieldDecl *FD = cast<FieldDecl>(D);
4346 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4347 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4348 } else if (isa<VarDecl>(D)) {
4349 VarDecl *VD = cast<VarDecl>(D);
4350 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4351 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4352
4353 // Nested classes and class templates.
4354 } else if (isa<CXXRecordDecl>(D)) {
4355 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4356 } else if (isa<ClassTemplateDecl>(D)) {
4357 CheckAbstractClassUsage(Info,
4358 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4359 }
4360 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004361}
4362
Douglas Gregorc99f1552009-12-03 18:33:45 +00004363/// \brief Perform semantic checks on a class definition that has been
4364/// completing, introducing implicitly-declared members, checking for
4365/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004366void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004367 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004368 return;
4369
John McCall02db245d2010-08-18 09:41:07 +00004370 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4371 AbstractUsageInfo Info(*this, Record);
4372 CheckAbstractClassUsage(Info, Record);
4373 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004374
4375 // If this is not an aggregate type and has no user-declared constructor,
4376 // complain about any non-static data members of reference or const scalar
4377 // type, since they will never get initializers.
4378 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004379 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4380 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004381 bool Complained = false;
4382 for (RecordDecl::field_iterator F = Record->field_begin(),
4383 FEnd = Record->field_end();
4384 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004385 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004386 continue;
4387
Douglas Gregor454a5b62010-04-15 00:00:53 +00004388 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004389 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004390 if (!Complained) {
4391 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4392 << Record->getTagKind() << Record;
4393 Complained = true;
4394 }
4395
4396 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4397 << F->getType()->isReferenceType()
4398 << F->getDeclName();
4399 }
4400 }
4401 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004402
Anders Carlssone771e762011-01-25 18:08:22 +00004403 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004404 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004405
4406 if (Record->getIdentifier()) {
4407 // C++ [class.mem]p13:
4408 // If T is the name of a class, then each of the following shall have a
4409 // name different from T:
4410 // - every member of every anonymous union that is a member of class T.
4411 //
4412 // C++ [class.mem]p14:
4413 // In addition, if class T has a user-declared constructor (12.1), every
4414 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004415 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4416 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4417 ++I) {
4418 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004419 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4420 isa<IndirectFieldDecl>(D)) {
4421 Diag(D->getLocation(), diag::err_member_name_of_class)
4422 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004423 break;
4424 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004425 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004426 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004427
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004428 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004429 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004430 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004431 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004432 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4433 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4434 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004435
David Majnemera5433082013-10-18 00:33:31 +00004436 if (Record->isAbstract()) {
4437 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4438 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4439 << FA->isSpelledAsSealed();
4440 DiagnoseAbstractType(Record);
4441 }
David Blaikie348df502012-09-21 03:21:07 +00004442 }
4443
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004444 if (!Record->isDependentType()) {
4445 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4446 MEnd = Record->method_end();
4447 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004448 // See if a method overloads virtual methods in a base
4449 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004450 if (!M->isStatic())
Eli Friedmanaf65120b2013-09-05 23:51:03 +00004451 DiagnoseHiddenVirtualMethods(*M);
Richard Smithbd305122012-12-11 01:14:52 +00004452
4453 // Check whether the explicitly-defaulted special members are valid.
4454 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4455 CheckExplicitlyDefaultedSpecialMember(*M);
4456
4457 // For an explicitly defaulted or deleted special member, we defer
4458 // determining triviality until the class is complete. That time is now!
4459 if (!M->isImplicit() && !M->isUserProvided()) {
4460 CXXSpecialMember CSM = getSpecialMember(*M);
4461 if (CSM != CXXInvalid) {
4462 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4463
4464 // Inform the class that we've finished declaring this member.
4465 Record->finishedDefaultedOrDeletedMember(*M);
4466 }
4467 }
4468 }
Hans Wennborge955e392013-12-17 17:49:22 +00004469
4470 if (Record->hasUserDeclaredDestructor()) {
4471 // The Microsoft ABI requires that we perform the destructor body
4472 // checks (i.e. operator delete() lookup) in any translataion unit, as
4473 // any translation unit may need to emit a deleting destructor.
4474 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4475 !Record->getDestructor()->isDeleted())
4476 CheckDestructor(Record->getDestructor());
4477 }
Richard Smithbd305122012-12-11 01:14:52 +00004478 }
4479
4480 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4481 // function that is not a constructor declares that member function to be
4482 // const. [...] The class of which that function is a member shall be
4483 // a literal type.
4484 //
4485 // If the class has virtual bases, any constexpr members will already have
4486 // been diagnosed by the checks performed on the member declaration, so
4487 // suppress this (less useful) diagnostic.
4488 //
4489 // We delay this until we know whether an explicitly-defaulted (or deleted)
4490 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004491 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004492 !Record->isLiteral() && !Record->getNumVBases()) {
4493 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4494 MEnd = Record->method_end();
4495 M != MEnd; ++M) {
4496 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4497 switch (Record->getTemplateSpecializationKind()) {
4498 case TSK_ImplicitInstantiation:
4499 case TSK_ExplicitInstantiationDeclaration:
4500 case TSK_ExplicitInstantiationDefinition:
4501 // If a template instantiates to a non-literal type, but its members
4502 // instantiate to constexpr functions, the template is technically
4503 // ill-formed, but we allow it for sanity.
4504 continue;
4505
4506 case TSK_Undeclared:
4507 case TSK_ExplicitSpecialization:
4508 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4509 diag::err_constexpr_method_non_literal);
4510 break;
4511 }
4512
4513 // Only produce one error per class.
4514 break;
4515 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004516 }
4517 }
Sebastian Redl08905022011-02-05 19:23:19 +00004518
Warren Hunt8f8bad72013-10-11 20:19:00 +00004519 // Check to see if we're trying to lay out a struct using the ms_struct
4520 // attribute that is dynamic.
4521 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4522 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4523 Record->dropAttr<MsStructAttr>();
4524 }
4525
Richard Smithc2bc61b2013-03-18 21:12:30 +00004526 // Declare inheriting constructors. We do this eagerly here because:
4527 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004528 // constructors from different classes.
4529 // - The lazy declaration of the other implicit constructors is so as to not
4530 // waste space and performance on classes that are not meant to be
4531 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004532 // have inheriting constructors.
4533 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004534}
4535
Richard Smith41c35d62013-11-27 03:39:20 +00004536/// Look up the special member function that would be called by a special
4537/// member function for a subobject of class type.
4538///
4539/// \param Class The class type of the subobject.
4540/// \param CSM The kind of special member function.
4541/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4542/// \param ConstRHS True if this is a copy operation with a const object
4543/// on its RHS, that is, if the argument to the outer special member
4544/// function is 'const' and this is not a field marked 'mutable'.
4545static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4546 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4547 unsigned FieldQuals, bool ConstRHS) {
4548 unsigned LHSQuals = 0;
4549 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4550 LHSQuals = FieldQuals;
4551
4552 unsigned RHSQuals = FieldQuals;
4553 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4554 RHSQuals = 0;
4555 else if (ConstRHS)
4556 RHSQuals |= Qualifiers::Const;
4557
4558 return S.LookupSpecialMember(Class, CSM,
4559 RHSQuals & Qualifiers::Const,
4560 RHSQuals & Qualifiers::Volatile,
4561 false,
4562 LHSQuals & Qualifiers::Const,
4563 LHSQuals & Qualifiers::Volatile);
4564}
4565
Richard Smithb5800092012-06-10 05:43:50 +00004566/// Is the special member function which would be selected to perform the
4567/// specified operation on the specified class type a constexpr constructor?
4568static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4569 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004570 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004571 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004572 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004573 if (!SMOR || !SMOR->getMethod())
4574 // A constructor we wouldn't select can't be "involved in initializing"
4575 // anything.
4576 return true;
4577 return SMOR->getMethod()->isConstexpr();
4578}
4579
4580/// Determine whether the specified special member function would be constexpr
4581/// if it were implicitly defined.
4582static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4583 Sema::CXXSpecialMember CSM,
4584 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004585 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004586 return false;
4587
4588 // C++11 [dcl.constexpr]p4:
4589 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004590 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004591 switch (CSM) {
4592 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004593 // Since default constructor lookup is essentially trivial (and cannot
4594 // involve, for instance, template instantiation), we compute whether a
4595 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4596 //
4597 // This is important for performance; we need to know whether the default
4598 // constructor is constexpr to determine whether the type is a literal type.
4599 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4600
Richard Smithb5800092012-06-10 05:43:50 +00004601 case Sema::CXXCopyConstructor:
4602 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004603 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004604 break;
4605
4606 case Sema::CXXCopyAssignment:
4607 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004608 if (!S.getLangOpts().CPlusPlus1y)
4609 return false;
4610 // In C++1y, we need to perform overload resolution.
4611 Ctor = false;
4612 break;
4613
Richard Smithb5800092012-06-10 05:43:50 +00004614 case Sema::CXXDestructor:
4615 case Sema::CXXInvalid:
4616 return false;
4617 }
4618
4619 // -- if the class is a non-empty union, or for each non-empty anonymous
4620 // union member of a non-union class, exactly one non-static data member
4621 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004622 //
4623 // If we squint, this is guaranteed, since exactly one non-static data member
4624 // will be initialized (if the constructor isn't deleted), we just don't know
4625 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004626 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004627 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004628
4629 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004630 if (Ctor && ClassDecl->getNumVBases())
4631 return false;
4632
4633 // C++1y [class.copy]p26:
4634 // -- [the class] is a literal type, and
4635 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004636 return false;
4637
4638 // -- every constructor involved in initializing [...] base class
4639 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004640 // -- the assignment operator selected to copy/move each direct base
4641 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004642 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4643 BEnd = ClassDecl->bases_end();
4644 B != BEnd; ++B) {
4645 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4646 if (!BaseType) continue;
4647
4648 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004649 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004650 return false;
4651 }
4652
4653 // -- every constructor involved in initializing non-static data members
4654 // [...] shall be a constexpr constructor;
4655 // -- every non-static data member and base class sub-object shall be
4656 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004657 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004658 // thereof), the assignment operator selected to copy/move that member is
4659 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004660 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4661 FEnd = ClassDecl->field_end();
4662 F != FEnd; ++F) {
4663 if (F->isInvalidDecl())
4664 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004665 QualType BaseType = S.Context.getBaseElementType(F->getType());
4666 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004667 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004668 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4669 BaseType.getCVRQualifiers(),
4670 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004671 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004672 }
4673 }
4674
4675 // All OK, it's constexpr!
4676 return true;
4677}
4678
Richard Smithd3b5c9082012-07-27 04:22:15 +00004679static Sema::ImplicitExceptionSpecification
4680computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4681 switch (S.getSpecialMember(MD)) {
4682 case Sema::CXXDefaultConstructor:
4683 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4684 case Sema::CXXCopyConstructor:
4685 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4686 case Sema::CXXCopyAssignment:
4687 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4688 case Sema::CXXMoveConstructor:
4689 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4690 case Sema::CXXMoveAssignment:
4691 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4692 case Sema::CXXDestructor:
4693 return S.ComputeDefaultedDtorExceptionSpec(MD);
4694 case Sema::CXXInvalid:
4695 break;
4696 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004697 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4698 "only special members have implicit exception specs");
4699 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004700}
4701
Richard Smith7f782272012-07-30 23:48:14 +00004702static void
4703updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4704 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4705 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4706 ExceptSpec.getEPI(EPI);
Richard Smith185be182013-04-10 05:48:59 +00004707 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4708 FPT->getArgTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004709}
4710
Reid Kleckner78af0702013-08-27 23:08:25 +00004711static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4712 CXXMethodDecl *MD) {
4713 FunctionProtoType::ExtProtoInfo EPI;
4714
4715 // Build an exception specification pointing back at this member.
4716 EPI.ExceptionSpecType = EST_Unevaluated;
4717 EPI.ExceptionSpecDecl = MD;
4718
4719 // Set the calling convention to the default for C++ instance methods.
4720 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4721 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4722 /*IsCXXMethod=*/true));
4723 return EPI;
4724}
4725
Richard Smithd3b5c9082012-07-27 04:22:15 +00004726void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4727 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4728 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4729 return;
4730
Richard Smith7f782272012-07-30 23:48:14 +00004731 // Evaluate the exception specification.
4732 ImplicitExceptionSpecification ExceptSpec =
4733 computeImplicitExceptionSpec(*this, Loc, MD);
4734
4735 // Update the type of the special member to use it.
4736 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4737
4738 // A user-provided destructor can be defined outside the class. When that
4739 // happens, be sure to update the exception specification on both
4740 // declarations.
4741 const FunctionProtoType *CanonicalFPT =
4742 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4743 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4744 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4745 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004746}
4747
Richard Smithb9e90b12012-05-15 04:39:51 +00004748void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4749 CXXRecordDecl *RD = MD->getParent();
4750 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004751
Richard Smithb9e90b12012-05-15 04:39:51 +00004752 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4753 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004754
4755 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004756 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004757 bool First = MD == MD->getCanonicalDecl();
4758
4759 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004760
4761 // C++11 [dcl.fct.def.default]p1:
4762 // A function that is explicitly defaulted shall
4763 // -- be a special member function (checked elsewhere),
4764 // -- have the same type (except for ref-qualifiers, and except that a
4765 // copy operation can take a non-const reference) as an implicit
4766 // declaration, and
4767 // -- not have default arguments.
4768 unsigned ExpectedParams = 1;
4769 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4770 ExpectedParams = 0;
4771 if (MD->getNumParams() != ExpectedParams) {
4772 // This also checks for default arguments: a copy or move constructor with a
4773 // default argument is classified as a default constructor, and assignment
4774 // operations and destructors can't have default arguments.
4775 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4776 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004777 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004778 } else if (MD->isVariadic()) {
4779 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4780 << CSM << MD->getSourceRange();
4781 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004782 }
4783
Richard Smithb9e90b12012-05-15 04:39:51 +00004784 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004785
Richard Smithb5800092012-06-10 05:43:50 +00004786 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004787 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004788 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004789 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004790 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004791
Richard Smithb9e90b12012-05-15 04:39:51 +00004792 QualType ReturnType = Context.VoidTy;
4793 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4794 // Check for return type matching.
4795 ReturnType = Type->getResultType();
4796 QualType ExpectedReturnType =
4797 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4798 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4799 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4800 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4801 HadError = true;
4802 }
4803
4804 // A defaulted special member cannot have cv-qualifiers.
4805 if (Type->getTypeQuals()) {
4806 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004807 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004808 HadError = true;
4809 }
4810 }
4811
4812 // Check for parameter type matching.
4813 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004814 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004815 if (ExpectedParams && ArgType->isReferenceType()) {
4816 // Argument must be reference to possibly-const T.
4817 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004818 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004819
4820 if (ReferentType.isVolatileQualified()) {
4821 Diag(MD->getLocation(),
4822 diag::err_defaulted_special_member_volatile_param) << CSM;
4823 HadError = true;
4824 }
4825
Richard Smithb5800092012-06-10 05:43:50 +00004826 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004827 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4828 Diag(MD->getLocation(),
4829 diag::err_defaulted_special_member_copy_const_param)
4830 << (CSM == CXXCopyAssignment);
4831 // FIXME: Explain why this special member can't be const.
4832 } else {
4833 Diag(MD->getLocation(),
4834 diag::err_defaulted_special_member_move_const_param)
4835 << (CSM == CXXMoveAssignment);
4836 }
4837 HadError = true;
4838 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004839 } else if (ExpectedParams) {
4840 // A copy assignment operator can take its argument by value, but a
4841 // defaulted one cannot.
4842 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004843 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004844 HadError = true;
4845 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004846
Richard Smithcc36f692011-12-22 02:22:31 +00004847 // C++11 [dcl.fct.def.default]p2:
4848 // An explicitly-defaulted function may be declared constexpr only if it
4849 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004850 // Do not apply this rule to members of class templates, since core issue 1358
4851 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004852 // functions which cannot be constexpr (for non-constructors in C++11 and for
4853 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004854 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4855 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004856 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4857 : isa<CXXConstructorDecl>(MD)) &&
4858 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004859 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4860 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004861 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004862 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004863 }
Richard Smithbd305122012-12-11 01:14:52 +00004864
Richard Smithcc36f692011-12-22 02:22:31 +00004865 // and may have an explicit exception-specification only if it is compatible
4866 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004867 if (Type->hasExceptionSpec()) {
4868 // Delay the check if this is the first declaration of the special member,
4869 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004870 if (First) {
4871 // If the exception specification needs to be instantiated, do so now,
4872 // before we clobber it with an EST_Unevaluated specification below.
4873 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4874 InstantiateExceptionSpec(MD->getLocStart(), MD);
4875 Type = MD->getType()->getAs<FunctionProtoType>();
4876 }
Richard Smithbd305122012-12-11 01:14:52 +00004877 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004878 } else
Richard Smithbd305122012-12-11 01:14:52 +00004879 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4880 }
Richard Smithcc36f692011-12-22 02:22:31 +00004881
4882 // If a function is explicitly defaulted on its first declaration,
4883 if (First) {
4884 // -- it is implicitly considered to be constexpr if the implicit
4885 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004886 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004887
Richard Smithb9e90b12012-05-15 04:39:51 +00004888 // -- it is implicitly considered to have the same exception-specification
4889 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004890 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4891 EPI.ExceptionSpecType = EST_Unevaluated;
4892 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004893 MD->setType(Context.getFunctionType(ReturnType,
4894 ArrayRef<QualType>(&ArgType,
4895 ExpectedParams),
4896 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004897 }
4898
Richard Smithb9e90b12012-05-15 04:39:51 +00004899 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004900 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004901 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004902 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004903 // C++11 [dcl.fct.def.default]p4:
4904 // [For a] user-provided explicitly-defaulted function [...] if such a
4905 // function is implicitly defined as deleted, the program is ill-formed.
4906 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4907 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004908 }
4909 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004910
Richard Smithb9e90b12012-05-15 04:39:51 +00004911 if (HadError)
4912 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004913}
4914
Richard Smithbd305122012-12-11 01:14:52 +00004915/// Check whether the exception specification provided for an
4916/// explicitly-defaulted special member matches the exception specification
4917/// that would have been generated for an implicit special member, per
4918/// C++11 [dcl.fct.def.default]p2.
4919void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4920 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4921 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004922 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4923 /*IsCXXMethod=*/true);
4924 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004925 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4926 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004927 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004928
4929 // Ensure that it matches.
4930 CheckEquivalentExceptionSpec(
4931 PDiag(diag::err_incorrect_defaulted_exception_spec)
4932 << getSpecialMember(MD), PDiag(),
4933 ImplicitType, SourceLocation(),
4934 SpecifiedType, MD->getLocation());
4935}
4936
Alp Tokerae3a9442013-10-18 05:54:19 +00004937void Sema::CheckDelayedMemberExceptionSpecs() {
4938 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4939 2> Checks;
4940 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004941
Alp Tokerae3a9442013-10-18 05:54:19 +00004942 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4943 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4944
4945 // Perform any deferred checking of exception specifications for virtual
4946 // destructors.
4947 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4948 const CXXDestructorDecl *Dtor = Checks[i].first;
4949 assert(!Dtor->getParent()->isDependentType() &&
4950 "Should not ever add destructors of templates into the list.");
4951 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4952 }
4953
4954 // Check that any explicitly-defaulted methods have exception specifications
4955 // compatible with their implicit exception specifications.
4956 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4957 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4958 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004959}
4960
Richard Smithd951a1d2012-02-18 02:02:13 +00004961namespace {
4962struct SpecialMemberDeletionInfo {
4963 Sema &S;
4964 CXXMethodDecl *MD;
4965 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004966 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004967
4968 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004969 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004970 SourceLocation Loc;
4971
4972 bool AllFieldsAreConst;
4973
4974 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004975 Sema::CXXSpecialMember CSM, bool Diagnose)
4976 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004977 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004978 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004979 AllFieldsAreConst(true) {
4980 switch (CSM) {
4981 case Sema::CXXDefaultConstructor:
4982 case Sema::CXXCopyConstructor:
4983 IsConstructor = true;
4984 break;
4985 case Sema::CXXMoveConstructor:
4986 IsConstructor = true;
4987 IsMove = true;
4988 break;
4989 case Sema::CXXCopyAssignment:
4990 IsAssignment = true;
4991 break;
4992 case Sema::CXXMoveAssignment:
4993 IsAssignment = true;
4994 IsMove = true;
4995 break;
4996 case Sema::CXXDestructor:
4997 break;
4998 case Sema::CXXInvalid:
4999 llvm_unreachable("invalid special member kind");
5000 }
5001
5002 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005003 if (const ReferenceType *RT =
5004 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5005 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005006 }
5007 }
5008
5009 bool inUnion() const { return MD->getParent()->isUnion(); }
5010
5011 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005012 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005013 unsigned Quals, bool IsMutable) {
5014 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5015 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005016 }
5017
Richard Smith852265f2012-03-30 20:53:28 +00005018 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005019
Richard Smith852265f2012-03-30 20:53:28 +00005020 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005021 bool shouldDeleteForField(FieldDecl *FD);
5022 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005023
Richard Smithaf136f82012-07-18 03:51:16 +00005024 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5025 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005026 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5027 Sema::SpecialMemberOverloadResult *SMOR,
5028 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005029
5030 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005031};
5032}
5033
John McCalld4274212012-04-09 20:53:23 +00005034/// Is the given special member inaccessible when used on the given
5035/// sub-object.
5036bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5037 CXXMethodDecl *target) {
5038 /// If we're operating on a base class, the object type is the
5039 /// type of this special member.
5040 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005041 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005042 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5043 objectTy = S.Context.getTypeDeclType(MD->getParent());
5044 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5045
5046 // If we're operating on a field, the object type is the type of the field.
5047 } else {
5048 objectTy = S.Context.getTypeDeclType(target->getParent());
5049 }
5050
5051 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5052}
5053
Richard Smith852265f2012-03-30 20:53:28 +00005054/// Check whether we should delete a special member due to the implicit
5055/// definition containing a call to a special member of a subobject.
5056bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5057 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5058 bool IsDtorCallInCtor) {
5059 CXXMethodDecl *Decl = SMOR->getMethod();
5060 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5061
5062 int DiagKind = -1;
5063
5064 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5065 DiagKind = !Decl ? 0 : 1;
5066 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5067 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005068 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005069 DiagKind = 3;
5070 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5071 !Decl->isTrivial()) {
5072 // A member of a union must have a trivial corresponding special member.
5073 // As a weird special case, a destructor call from a union's constructor
5074 // must be accessible and non-deleted, but need not be trivial. Such a
5075 // destructor is never actually called, but is semantically checked as
5076 // if it were.
5077 DiagKind = 4;
5078 }
5079
5080 if (DiagKind == -1)
5081 return false;
5082
5083 if (Diagnose) {
5084 if (Field) {
5085 S.Diag(Field->getLocation(),
5086 diag::note_deleted_special_member_class_subobject)
5087 << CSM << MD->getParent() << /*IsField*/true
5088 << Field << DiagKind << IsDtorCallInCtor;
5089 } else {
5090 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5091 S.Diag(Base->getLocStart(),
5092 diag::note_deleted_special_member_class_subobject)
5093 << CSM << MD->getParent() << /*IsField*/false
5094 << Base->getType() << DiagKind << IsDtorCallInCtor;
5095 }
5096
5097 if (DiagKind == 1)
5098 S.NoteDeletedFunction(Decl);
5099 // FIXME: Explain inaccessibility if DiagKind == 3.
5100 }
5101
5102 return true;
5103}
5104
Richard Smith921bd202012-02-26 09:11:52 +00005105/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005106/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005107bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005108 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005109 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005110 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005111
5112 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005113 // -- any direct or virtual base class, or non-static data member with no
5114 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005115 // either M has no default constructor or overload resolution as applied
5116 // to M's default constructor results in an ambiguity or in a function
5117 // that is deleted or inaccessible
5118 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5119 // -- a direct or virtual base class B that cannot be copied/moved because
5120 // overload resolution, as applied to B's corresponding special member,
5121 // results in an ambiguity or a function that is deleted or inaccessible
5122 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005123 // C++11 [class.dtor]p5:
5124 // -- any direct or virtual base class [...] has a type with a destructor
5125 // that is deleted or inaccessible
5126 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005127 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005128 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5129 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005130 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005131
Richard Smith852265f2012-03-30 20:53:28 +00005132 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5133 // -- any direct or virtual base class or non-static data member has a
5134 // type with a destructor that is deleted or inaccessible
5135 if (IsConstructor) {
5136 Sema::SpecialMemberOverloadResult *SMOR =
5137 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5138 false, false, false, false, false);
5139 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5140 return true;
5141 }
5142
Richard Smith921bd202012-02-26 09:11:52 +00005143 return false;
5144}
5145
5146/// Check whether we should delete a special member function due to the class
5147/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005148bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005149 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005150 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005151}
5152
5153/// Check whether we should delete a special member function due to the class
5154/// having a particular non-static data member.
5155bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5156 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5157 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5158
5159 if (CSM == Sema::CXXDefaultConstructor) {
5160 // For a default constructor, all references must be initialized in-class
5161 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005162 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5163 if (Diagnose)
5164 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5165 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005166 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005167 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005168 // C++11 [class.ctor]p5: any non-variant non-static data member of
5169 // const-qualified type (or array thereof) with no
5170 // brace-or-equal-initializer does not have a user-provided default
5171 // constructor.
5172 if (!inUnion() && FieldType.isConstQualified() &&
5173 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005174 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5175 if (Diagnose)
5176 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005177 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005178 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005179 }
5180
5181 if (inUnion() && !FieldType.isConstQualified())
5182 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005183 } else if (CSM == Sema::CXXCopyConstructor) {
5184 // For a copy constructor, data members must not be of rvalue reference
5185 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005186 if (FieldType->isRValueReferenceType()) {
5187 if (Diagnose)
5188 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5189 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005190 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005191 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005192 } else if (IsAssignment) {
5193 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005194 if (FieldType->isReferenceType()) {
5195 if (Diagnose)
5196 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5197 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005198 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005199 }
5200 if (!FieldRecord && FieldType.isConstQualified()) {
5201 // C++11 [class.copy]p23:
5202 // -- a non-static data member of const non-class type (or array thereof)
5203 if (Diagnose)
5204 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005205 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005206 return true;
5207 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005208 }
5209
5210 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005211 // Some additional restrictions exist on the variant members.
5212 if (!inUnion() && FieldRecord->isUnion() &&
5213 FieldRecord->isAnonymousStructOrUnion()) {
5214 bool AllVariantFieldsAreConst = true;
5215
Richard Smith5704fe82012-03-29 19:00:10 +00005216 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00005217 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5218 UE = FieldRecord->field_end();
5219 UI != UE; ++UI) {
5220 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005221
5222 if (!UnionFieldType.isConstQualified())
5223 AllVariantFieldsAreConst = false;
5224
Richard Smith921bd202012-02-26 09:11:52 +00005225 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5226 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00005227 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5228 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005229 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005230 }
5231
5232 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005233 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00005234 FieldRecord->field_begin() != FieldRecord->field_end()) {
5235 if (Diagnose)
5236 S.Diag(FieldRecord->getLocation(),
5237 diag::note_deleted_default_ctor_all_const)
5238 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005239 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005240 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005241
Richard Smith5704fe82012-03-29 19:00:10 +00005242 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005243 // This is technically non-conformant, but sanity demands it.
5244 return false;
5245 }
5246
Richard Smithaf136f82012-07-18 03:51:16 +00005247 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5248 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005249 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005250 }
5251
5252 return false;
5253}
5254
5255/// C++11 [class.ctor] p5:
5256/// A defaulted default constructor for a class X is defined as deleted if
5257/// X is a union and all of its variant members are of const-qualified type.
5258bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005259 // This is a silly definition, because it gives an empty union a deleted
5260 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005261 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5262 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5263 if (Diagnose)
5264 S.Diag(MD->getParent()->getLocation(),
5265 diag::note_deleted_default_ctor_all_const)
5266 << MD->getParent() << /*not anonymous union*/0;
5267 return true;
5268 }
5269 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005270}
5271
5272/// Determine whether a defaulted special member function should be defined as
5273/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5274/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005275bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5276 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005277 if (MD->isInvalidDecl())
5278 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005279 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005280 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005281 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005282 return false;
5283
Richard Smithd951a1d2012-02-18 02:02:13 +00005284 // C++11 [expr.lambda.prim]p19:
5285 // The closure type associated with a lambda-expression has a
5286 // deleted (8.4.3) default constructor and a deleted copy
5287 // assignment operator.
5288 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005289 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5290 if (Diagnose)
5291 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005292 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005293 }
5294
Richard Smith6f1e2c62012-04-02 20:59:25 +00005295 // For an anonymous struct or union, the copy and assignment special members
5296 // will never be used, so skip the check. For an anonymous union declared at
5297 // namespace scope, the constructor and destructor are used.
5298 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5299 RD->isAnonymousStructOrUnion())
5300 return false;
5301
Richard Smith852265f2012-03-30 20:53:28 +00005302 // C++11 [class.copy]p7, p18:
5303 // If the class definition declares a move constructor or move assignment
5304 // operator, an implicitly declared copy constructor or copy assignment
5305 // operator is defined as deleted.
5306 if (MD->isImplicit() &&
5307 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5308 CXXMethodDecl *UserDeclaredMove = 0;
5309
5310 // In Microsoft mode, a user-declared move only causes the deletion of the
5311 // corresponding copy operation, not both copy operations.
5312 if (RD->hasUserDeclaredMoveConstructor() &&
5313 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5314 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005315
5316 // Find any user-declared move constructor.
5317 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5318 E = RD->ctor_end(); I != E; ++I) {
5319 if (I->isMoveConstructor()) {
5320 UserDeclaredMove = *I;
5321 break;
5322 }
5323 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005324 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005325 } else if (RD->hasUserDeclaredMoveAssignment() &&
5326 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5327 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005328
5329 // Find any user-declared move assignment operator.
5330 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5331 E = RD->method_end(); I != E; ++I) {
5332 if (I->isMoveAssignmentOperator()) {
5333 UserDeclaredMove = *I;
5334 break;
5335 }
5336 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005337 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005338 }
5339
5340 if (UserDeclaredMove) {
5341 Diag(UserDeclaredMove->getLocation(),
5342 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005343 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005344 << UserDeclaredMove->isMoveAssignmentOperator();
5345 return true;
5346 }
5347 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005348
Richard Smith6f1e2c62012-04-02 20:59:25 +00005349 // Do access control from the special member function
5350 ContextRAII MethodContext(*this, MD);
5351
Richard Smith921bd202012-02-26 09:11:52 +00005352 // C++11 [class.dtor]p5:
5353 // -- for a virtual destructor, lookup of the non-array deallocation function
5354 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005355 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005356 FunctionDecl *OperatorDelete = 0;
5357 DeclarationName Name =
5358 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5359 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005360 OperatorDelete, false)) {
5361 if (Diagnose)
5362 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005363 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005364 }
Richard Smith921bd202012-02-26 09:11:52 +00005365 }
5366
Richard Smith852265f2012-03-30 20:53:28 +00005367 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005368
Alexis Huntea6f0322011-05-11 22:34:38 +00005369 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005370 BE = RD->bases_end(); BI != BE; ++BI)
5371 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005372 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005373 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005374
Richard Smithd1627032013-07-22 18:06:23 +00005375 // Per DR1611, do not consider virtual bases of constructors of abstract
5376 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005377 if (!RD->isAbstract() || !SMI.IsConstructor) {
5378 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5379 BE = RD->vbases_end();
5380 BI != BE; ++BI)
5381 if (SMI.shouldDeleteForBase(BI))
5382 return true;
5383 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005384
5385 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005386 FE = RD->field_end(); FI != FE; ++FI)
5387 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005388 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005389 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005390
Richard Smithd951a1d2012-02-18 02:02:13 +00005391 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005392 return true;
5393
5394 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005395}
5396
Richard Smith92f241f2012-12-08 02:53:02 +00005397/// Perform lookup for a special member of the specified kind, and determine
5398/// whether it is trivial. If the triviality can be determined without the
5399/// lookup, skip it. This is intended for use when determining whether a
5400/// special member of a containing object is trivial, and thus does not ever
5401/// perform overload resolution for default constructors.
5402///
5403/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5404/// member that was most likely to be intended to be trivial, if any.
5405static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5406 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005407 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005408 if (Selected)
5409 *Selected = 0;
5410
5411 switch (CSM) {
5412 case Sema::CXXInvalid:
5413 llvm_unreachable("not a special member");
5414
5415 case Sema::CXXDefaultConstructor:
5416 // C++11 [class.ctor]p5:
5417 // A default constructor is trivial if:
5418 // - all the [direct subobjects] have trivial default constructors
5419 //
5420 // Note, no overload resolution is performed in this case.
5421 if (RD->hasTrivialDefaultConstructor())
5422 return true;
5423
5424 if (Selected) {
5425 // If there's a default constructor which could have been trivial, dig it
5426 // out. Otherwise, if there's any user-provided default constructor, point
5427 // to that as an example of why there's not a trivial one.
5428 CXXConstructorDecl *DefCtor = 0;
5429 if (RD->needsImplicitDefaultConstructor())
5430 S.DeclareImplicitDefaultConstructor(RD);
5431 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5432 CE = RD->ctor_end(); CI != CE; ++CI) {
5433 if (!CI->isDefaultConstructor())
5434 continue;
5435 DefCtor = *CI;
5436 if (!DefCtor->isUserProvided())
5437 break;
5438 }
5439
5440 *Selected = DefCtor;
5441 }
5442
5443 return false;
5444
5445 case Sema::CXXDestructor:
5446 // C++11 [class.dtor]p5:
5447 // A destructor is trivial if:
5448 // - all the direct [subobjects] have trivial destructors
5449 if (RD->hasTrivialDestructor())
5450 return true;
5451
5452 if (Selected) {
5453 if (RD->needsImplicitDestructor())
5454 S.DeclareImplicitDestructor(RD);
5455 *Selected = RD->getDestructor();
5456 }
5457
5458 return false;
5459
5460 case Sema::CXXCopyConstructor:
5461 // C++11 [class.copy]p12:
5462 // A copy constructor is trivial if:
5463 // - the constructor selected to copy each direct [subobject] is trivial
5464 if (RD->hasTrivialCopyConstructor()) {
5465 if (Quals == Qualifiers::Const)
5466 // We must either select the trivial copy constructor or reach an
5467 // ambiguity; no need to actually perform overload resolution.
5468 return true;
5469 } else if (!Selected) {
5470 return false;
5471 }
5472 // In C++98, we are not supposed to perform overload resolution here, but we
5473 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5474 // cases like B as having a non-trivial copy constructor:
5475 // struct A { template<typename T> A(T&); };
5476 // struct B { mutable A a; };
5477 goto NeedOverloadResolution;
5478
5479 case Sema::CXXCopyAssignment:
5480 // C++11 [class.copy]p25:
5481 // A copy assignment operator is trivial if:
5482 // - the assignment operator selected to copy each direct [subobject] is
5483 // trivial
5484 if (RD->hasTrivialCopyAssignment()) {
5485 if (Quals == Qualifiers::Const)
5486 return true;
5487 } else if (!Selected) {
5488 return false;
5489 }
5490 // In C++98, we are not supposed to perform overload resolution here, but we
5491 // treat that as a language defect.
5492 goto NeedOverloadResolution;
5493
5494 case Sema::CXXMoveConstructor:
5495 case Sema::CXXMoveAssignment:
5496 NeedOverloadResolution:
5497 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005498 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005499
5500 // The standard doesn't describe how to behave if the lookup is ambiguous.
5501 // We treat it as not making the member non-trivial, just like the standard
5502 // mandates for the default constructor. This should rarely matter, because
5503 // the member will also be deleted.
5504 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5505 return true;
5506
5507 if (!SMOR->getMethod()) {
5508 assert(SMOR->getKind() ==
5509 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5510 return false;
5511 }
5512
5513 // We deliberately don't check if we found a deleted special member. We're
5514 // not supposed to!
5515 if (Selected)
5516 *Selected = SMOR->getMethod();
5517 return SMOR->getMethod()->isTrivial();
5518 }
5519
5520 llvm_unreachable("unknown special method kind");
5521}
5522
Benjamin Kramer3e350262013-02-15 12:30:38 +00005523static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005524 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5525 CI != CE; ++CI)
5526 if (!CI->isImplicit())
5527 return *CI;
5528
5529 // Look for constructor templates.
5530 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5531 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5532 if (CXXConstructorDecl *CD =
5533 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5534 return CD;
5535 }
5536
5537 return 0;
5538}
5539
5540/// The kind of subobject we are checking for triviality. The values of this
5541/// enumeration are used in diagnostics.
5542enum TrivialSubobjectKind {
5543 /// The subobject is a base class.
5544 TSK_BaseClass,
5545 /// The subobject is a non-static data member.
5546 TSK_Field,
5547 /// The object is actually the complete object.
5548 TSK_CompleteObject
5549};
5550
5551/// Check whether the special member selected for a given type would be trivial.
5552static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005553 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005554 Sema::CXXSpecialMember CSM,
5555 TrivialSubobjectKind Kind,
5556 bool Diagnose) {
5557 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5558 if (!SubRD)
5559 return true;
5560
5561 CXXMethodDecl *Selected;
5562 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005563 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005564 return true;
5565
5566 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005567 if (ConstRHS)
5568 SubType.addConst();
5569
Richard Smith92f241f2012-12-08 02:53:02 +00005570 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5571 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5572 << Kind << SubType.getUnqualifiedType();
5573 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5574 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5575 } else if (!Selected)
5576 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5577 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5578 else if (Selected->isUserProvided()) {
5579 if (Kind == TSK_CompleteObject)
5580 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5581 << Kind << SubType.getUnqualifiedType() << CSM;
5582 else {
5583 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5584 << Kind << SubType.getUnqualifiedType() << CSM;
5585 S.Diag(Selected->getLocation(), diag::note_declared_at);
5586 }
5587 } else {
5588 if (Kind != TSK_CompleteObject)
5589 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5590 << Kind << SubType.getUnqualifiedType() << CSM;
5591
5592 // Explain why the defaulted or deleted special member isn't trivial.
5593 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5594 }
5595 }
5596
5597 return false;
5598}
5599
5600/// Check whether the members of a class type allow a special member to be
5601/// trivial.
5602static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5603 Sema::CXXSpecialMember CSM,
5604 bool ConstArg, bool Diagnose) {
5605 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5606 FE = RD->field_end(); FI != FE; ++FI) {
5607 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5608 continue;
5609
5610 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5611
5612 // Pretend anonymous struct or union members are members of this class.
5613 if (FI->isAnonymousStructOrUnion()) {
5614 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5615 CSM, ConstArg, Diagnose))
5616 return false;
5617 continue;
5618 }
5619
5620 // C++11 [class.ctor]p5:
5621 // A default constructor is trivial if [...]
5622 // -- no non-static data member of its class has a
5623 // brace-or-equal-initializer
5624 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5625 if (Diagnose)
5626 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5627 return false;
5628 }
5629
5630 // Objective C ARC 4.3.5:
5631 // [...] nontrivally ownership-qualified types are [...] not trivially
5632 // default constructible, copy constructible, move constructible, copy
5633 // assignable, move assignable, or destructible [...]
5634 if (S.getLangOpts().ObjCAutoRefCount &&
5635 FieldType.hasNonTrivialObjCLifetime()) {
5636 if (Diagnose)
5637 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5638 << RD << FieldType.getObjCLifetime();
5639 return false;
5640 }
5641
Richard Smith41c35d62013-11-27 03:39:20 +00005642 bool ConstRHS = ConstArg && !FI->isMutable();
5643 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5644 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005645 return false;
5646 }
5647
5648 return true;
5649}
5650
5651/// Diagnose why the specified class does not have a trivial special member of
5652/// the given kind.
5653void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5654 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005655
Richard Smith41c35d62013-11-27 03:39:20 +00005656 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5657 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005658 TSK_CompleteObject, /*Diagnose*/true);
5659}
5660
5661/// Determine whether a defaulted or deleted special member function is trivial,
5662/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5663/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5664bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5665 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005666 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5667
5668 CXXRecordDecl *RD = MD->getParent();
5669
5670 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005671
Richard Smith2002bfe2013-11-04 02:02:27 +00005672 // C++11 [class.copy]p12, p25: [DR1593]
5673 // A [special member] is trivial if [...] its parameter-type-list is
5674 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005675 switch (CSM) {
5676 case CXXDefaultConstructor:
5677 case CXXDestructor:
5678 // Trivial default constructors and destructors cannot have parameters.
5679 break;
5680
5681 case CXXCopyConstructor:
5682 case CXXCopyAssignment: {
5683 // Trivial copy operations always have const, non-volatile parameter types.
5684 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005685 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005686 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5687 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5688 if (Diagnose)
5689 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5690 << Param0->getSourceRange() << Param0->getType()
5691 << Context.getLValueReferenceType(
5692 Context.getRecordType(RD).withConst());
5693 return false;
5694 }
5695 break;
5696 }
5697
5698 case CXXMoveConstructor:
5699 case CXXMoveAssignment: {
5700 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005701 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005702 const RValueReferenceType *RT =
5703 Param0->getType()->getAs<RValueReferenceType>();
5704 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5705 if (Diagnose)
5706 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5707 << Param0->getSourceRange() << Param0->getType()
5708 << Context.getRValueReferenceType(Context.getRecordType(RD));
5709 return false;
5710 }
5711 break;
5712 }
5713
5714 case CXXInvalid:
5715 llvm_unreachable("not a special member");
5716 }
5717
Richard Smith92f241f2012-12-08 02:53:02 +00005718 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5719 if (Diagnose)
5720 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5721 diag::note_nontrivial_default_arg)
5722 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5723 return false;
5724 }
5725 if (MD->isVariadic()) {
5726 if (Diagnose)
5727 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5728 return false;
5729 }
5730
5731 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5732 // A copy/move [constructor or assignment operator] is trivial if
5733 // -- the [member] selected to copy/move each direct base class subobject
5734 // is trivial
5735 //
5736 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5737 // A [default constructor or destructor] is trivial if
5738 // -- all the direct base classes have trivial [default constructors or
5739 // destructors]
5740 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5741 BE = RD->bases_end(); BI != BE; ++BI)
Richard Smith41c35d62013-11-27 03:39:20 +00005742 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(),
5743 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005744 return false;
5745
5746 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5747 // A copy/move [constructor or assignment operator] for a class X is
5748 // trivial if
5749 // -- for each non-static data member of X that is of class type (or array
5750 // thereof), the constructor selected to copy/move that member is
5751 // trivial
5752 //
5753 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5754 // A [default constructor or destructor] is trivial if
5755 // -- for all of the non-static data members of its class that are of class
5756 // type (or array thereof), each such class has a trivial [default
5757 // constructor or destructor]
5758 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5759 return false;
5760
5761 // C++11 [class.dtor]p5:
5762 // A destructor is trivial if [...]
5763 // -- the destructor is not virtual
5764 if (CSM == CXXDestructor && MD->isVirtual()) {
5765 if (Diagnose)
5766 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5767 return false;
5768 }
5769
5770 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5771 // A [special member] for class X is trivial if [...]
5772 // -- class X has no virtual functions and no virtual base classes
5773 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5774 if (!Diagnose)
5775 return false;
5776
5777 if (RD->getNumVBases()) {
5778 // Check for virtual bases. We already know that the corresponding
5779 // member in all bases is trivial, so vbases must all be direct.
5780 CXXBaseSpecifier &BS = *RD->vbases_begin();
5781 assert(BS.isVirtual());
5782 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5783 return false;
5784 }
5785
5786 // Must have a virtual method.
5787 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5788 ME = RD->method_end(); MI != ME; ++MI) {
5789 if (MI->isVirtual()) {
5790 SourceLocation MLoc = MI->getLocStart();
5791 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5792 return false;
5793 }
5794 }
5795
5796 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5797 }
5798
5799 // Looks like it's trivial!
5800 return true;
5801}
5802
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005803/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005804namespace {
5805 struct FindHiddenVirtualMethodData {
5806 Sema *S;
5807 CXXMethodDecl *Method;
5808 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005809 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005810 };
5811}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005812
David Blaikie282c92a2012-10-19 00:53:08 +00005813/// \brief Check whether any most overriden method from MD in Methods
5814static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5815 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5816 if (MD->size_overridden_methods() == 0)
5817 return Methods.count(MD->getCanonicalDecl());
5818 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5819 E = MD->end_overridden_methods();
5820 I != E; ++I)
5821 if (CheckMostOverridenMethods(*I, Methods))
5822 return true;
5823 return false;
5824}
5825
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005826/// \brief Member lookup function that determines whether a given C++
5827/// method overloads virtual methods in a base class without overriding any,
5828/// to be used with CXXRecordDecl::lookupInBases().
5829static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5830 CXXBasePath &Path,
5831 void *UserData) {
5832 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5833
5834 FindHiddenVirtualMethodData &Data
5835 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5836
5837 DeclarationName Name = Data.Method->getDeclName();
5838 assert(Name.getNameKind() == DeclarationName::Identifier);
5839
5840 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005841 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005842 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005843 !Path.Decls.empty();
5844 Path.Decls = Path.Decls.slice(1)) {
5845 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005846 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005847 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005848 foundSameNameMethod = true;
5849 // Interested only in hidden virtual methods.
5850 if (!MD->isVirtual())
5851 continue;
5852 // If the method we are checking overrides a method from its base
5853 // don't warn about the other overloaded methods.
5854 if (!Data.S->IsOverload(Data.Method, MD, false))
5855 return true;
5856 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005857 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005858 overloadedMethods.push_back(MD);
5859 }
5860 }
5861
5862 if (foundSameNameMethod)
5863 Data.OverloadedMethods.append(overloadedMethods.begin(),
5864 overloadedMethods.end());
5865 return foundSameNameMethod;
5866}
5867
David Blaikie282c92a2012-10-19 00:53:08 +00005868/// \brief Add the most overriden methods from MD to Methods
5869static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5870 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5871 if (MD->size_overridden_methods() == 0)
5872 Methods.insert(MD->getCanonicalDecl());
5873 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5874 E = MD->end_overridden_methods();
5875 I != E; ++I)
5876 AddMostOverridenMethods(*I, Methods);
5877}
5878
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005879/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005880/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005881void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5882 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005883 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005884 return;
5885
5886 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5887 /*bool RecordPaths=*/false,
5888 /*bool DetectVirtual=*/false);
5889 FindHiddenVirtualMethodData Data;
5890 Data.Method = MD;
5891 Data.S = this;
5892
5893 // Keep the base methods that were overriden or introduced in the subclass
5894 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005895 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005896 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5897 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5898 NamedDecl *ND = *I;
5899 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005900 ND = shad->getTargetDecl();
5901 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5902 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005903 }
5904
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005905 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5906 OverloadedMethods = Data.OverloadedMethods;
5907}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005908
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005909void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5910 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5911 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5912 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5913 PartialDiagnostic PD = PDiag(
5914 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5915 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5916 Diag(overloadedMD->getLocation(), PD);
5917 }
5918}
5919
5920/// \brief Diagnose methods which overload virtual methods in a base class
5921/// without overriding any.
5922void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5923 if (MD->isInvalidDecl())
5924 return;
5925
5926 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5927 MD->getLocation()) == DiagnosticsEngine::Ignored)
5928 return;
5929
5930 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5931 FindHiddenVirtualMethods(MD, OverloadedMethods);
5932 if (!OverloadedMethods.empty()) {
5933 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5934 << MD << (OverloadedMethods.size() > 1);
5935
5936 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005937 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005938}
5939
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005940void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005941 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005942 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005943 SourceLocation RBrac,
5944 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005945 if (!TagDecl)
5946 return;
Mike Stump11289f42009-09-09 15:08:12 +00005947
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005948 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005949
Rafael Espindola06e1b132012-07-12 04:32:30 +00005950 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5951 if (l->getKind() != AttributeList::AT_Visibility)
5952 continue;
5953 l->setInvalid();
5954 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5955 l->getName();
5956 }
5957
David Blaikie751c5582011-09-22 02:58:26 +00005958 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005959 // strict aliasing violation!
5960 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005961 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005962
Douglas Gregor0be31a22010-07-02 17:43:08 +00005963 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005964 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005965}
5966
Douglas Gregor05379422008-11-03 17:51:48 +00005967/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5968/// special functions, such as the default constructor, copy
5969/// constructor, or destructor, to the given C++ class (C++
5970/// [special]p1). This routine can only be executed just before the
5971/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005972void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005973 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005974 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005975
Richard Smith6b02d462012-12-08 08:32:28 +00005976 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005977 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005978
Richard Smith6b02d462012-12-08 08:32:28 +00005979 // If the properties or semantics of the copy constructor couldn't be
5980 // determined while the class was being declared, force a declaration
5981 // of it now.
5982 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5983 DeclareImplicitCopyConstructor(ClassDecl);
5984 }
5985
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005986 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005987 ++ASTContext::NumImplicitMoveConstructors;
5988
Richard Smith6b02d462012-12-08 08:32:28 +00005989 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5990 DeclareImplicitMoveConstructor(ClassDecl);
5991 }
5992
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005993 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5994 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005995
5996 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005997 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005998 // it shows up in the right place in the vtable and that we diagnose
5999 // problems with the implicit exception specification.
6000 if (ClassDecl->isDynamicClass() ||
6001 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006002 DeclareImplicitCopyAssignment(ClassDecl);
6003 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006004
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006005 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006006 ++ASTContext::NumImplicitMoveAssignmentOperators;
6007
6008 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006009 if (ClassDecl->isDynamicClass() ||
6010 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006011 DeclareImplicitMoveAssignment(ClassDecl);
6012 }
6013
Douglas Gregor7454c562010-07-02 20:37:36 +00006014 if (!ClassDecl->hasUserDeclaredDestructor()) {
6015 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006016
6017 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006018 // have to declare the destructor immediately. This ensures that, e.g., it
6019 // shows up in the right place in the vtable and that we diagnose problems
6020 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006021 if (ClassDecl->isDynamicClass() ||
6022 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006023 DeclareImplicitDestructor(ClassDecl);
6024 }
Douglas Gregor05379422008-11-03 17:51:48 +00006025}
6026
Francois Pichet1c229c02011-04-22 22:18:13 +00006027void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
6028 if (!D)
6029 return;
6030
6031 int NumParamList = D->getNumTemplateParameterLists();
6032 for (int i = 0; i < NumParamList; i++) {
6033 TemplateParameterList* Params = D->getTemplateParameterList(i);
6034 for (TemplateParameterList::iterator Param = Params->begin(),
6035 ParamEnd = Params->end();
6036 Param != ParamEnd; ++Param) {
6037 NamedDecl *Named = cast<NamedDecl>(*Param);
6038 if (Named->getDeclName()) {
6039 S->AddDecl(Named);
6040 IdResolver.AddDecl(Named);
6041 }
6042 }
6043 }
6044}
6045
John McCall48871652010-08-21 09:40:31 +00006046void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00006047 if (!D)
6048 return;
6049
6050 TemplateParameterList *Params = 0;
6051 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6052 Params = Template->getTemplateParameters();
6053 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6054 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6055 Params = PartialSpec->getTemplateParameters();
6056 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006057 return;
6058
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006059 for (TemplateParameterList::iterator Param = Params->begin(),
6060 ParamEnd = Params->end();
6061 Param != ParamEnd; ++Param) {
6062 NamedDecl *Named = cast<NamedDecl>(*Param);
6063 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006064 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006065 IdResolver.AddDecl(Named);
6066 }
6067 }
6068}
6069
John McCall48871652010-08-21 09:40:31 +00006070void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006071 if (!RecordD) return;
6072 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006073 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006074 PushDeclContext(S, Record);
6075}
6076
John McCall48871652010-08-21 09:40:31 +00006077void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006078 if (!RecordD) return;
6079 PopDeclContext();
6080}
6081
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006082/// This is used to implement the constant expression evaluation part of the
6083/// attribute enable_if extension. There is nothing in standard C++ which would
6084/// require reentering parameters.
6085void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6086 if (!Param)
6087 return;
6088
6089 S->AddDecl(Param);
6090 if (Param->getDeclName())
6091 IdResolver.AddDecl(Param);
6092}
6093
Douglas Gregor4d87df52008-12-16 21:30:33 +00006094/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6095/// parsing a top-level (non-nested) C++ class, and we are now
6096/// parsing those parts of the given Method declaration that could
6097/// not be parsed earlier (C++ [class.mem]p2), such as default
6098/// arguments. This action should enter the scope of the given
6099/// Method declaration as if we had just parsed the qualified method
6100/// name. However, it should not bring the parameters into scope;
6101/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006102void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006103}
6104
6105/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6106/// C++ method declaration. We're (re-)introducing the given
6107/// function parameter into scope for use in parsing later parts of
6108/// the method declaration. For example, we could see an
6109/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006110void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006111 if (!ParamD)
6112 return;
Mike Stump11289f42009-09-09 15:08:12 +00006113
John McCall48871652010-08-21 09:40:31 +00006114 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006115
6116 // If this parameter has an unparsed default argument, clear it out
6117 // to make way for the parsed default argument.
6118 if (Param->hasUnparsedDefaultArg())
6119 Param->setDefaultArg(0);
6120
John McCall48871652010-08-21 09:40:31 +00006121 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006122 if (Param->getDeclName())
6123 IdResolver.AddDecl(Param);
6124}
6125
6126/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6127/// processing the delayed method declaration for Method. The method
6128/// declaration is now considered finished. There may be a separate
6129/// ActOnStartOfFunctionDef action later (not necessarily
6130/// immediately!) for this method, if it was also defined inside the
6131/// class body.
John McCall48871652010-08-21 09:40:31 +00006132void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006133 if (!MethodD)
6134 return;
Mike Stump11289f42009-09-09 15:08:12 +00006135
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006136 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006137
John McCall48871652010-08-21 09:40:31 +00006138 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006139
6140 // Now that we have our default arguments, check the constructor
6141 // again. It could produce additional diagnostics or affect whether
6142 // the class has implicitly-declared destructors, among other
6143 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006144 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6145 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006146
6147 // Check the default arguments, which we may have added.
6148 if (!Method->isInvalidDecl())
6149 CheckCXXDefaultArguments(Method);
6150}
6151
Douglas Gregor831c93f2008-11-05 20:51:48 +00006152/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006153/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006154/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006155/// emit diagnostics and set the invalid bit to true. In any case, the type
6156/// will be updated to reflect a well-formed type for the constructor and
6157/// returned.
6158QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006159 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006160 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006161
6162 // C++ [class.ctor]p3:
6163 // A constructor shall not be virtual (10.3) or static (9.4). A
6164 // constructor can be invoked for a const, volatile or const
6165 // volatile object. A constructor shall not be declared const,
6166 // volatile, or const volatile (9.3.2).
6167 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006168 if (!D.isInvalidType())
6169 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6170 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6171 << SourceRange(D.getIdentifierLoc());
6172 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006173 }
John McCall8e7d6562010-08-26 03:08:43 +00006174 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006175 if (!D.isInvalidType())
6176 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6177 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6178 << SourceRange(D.getIdentifierLoc());
6179 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006180 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006181 }
Mike Stump11289f42009-09-09 15:08:12 +00006182
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006183 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006184 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006185 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006186 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6187 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006188 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006189 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6190 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006191 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006192 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6193 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006194 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
Douglas Gregordb9d6642011-01-26 05:01:58 +00006197 // C++0x [class.ctor]p4:
6198 // A constructor shall not be declared with a ref-qualifier.
6199 if (FTI.hasRefQualifier()) {
6200 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6201 << FTI.RefQualifierIsLValueRef
6202 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6203 D.setInvalidType();
6204 }
6205
Douglas Gregor831c93f2008-11-05 20:51:48 +00006206 // Rebuild the function type "R" without any type qualifiers (in
6207 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006208 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006209 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006210 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6211 return R;
6212
6213 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6214 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006215 EPI.RefQualifier = RQ_None;
6216
Richard Smithc2bc61b2013-03-18 21:12:30 +00006217 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006218}
6219
Douglas Gregor4d87df52008-12-16 21:30:33 +00006220/// CheckConstructor - Checks a fully-formed constructor for
6221/// well-formedness, issuing any diagnostics required. Returns true if
6222/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006223void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006224 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006225 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6226 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006227 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006228
6229 // C++ [class.copy]p3:
6230 // A declaration of a constructor for a class X is ill-formed if
6231 // its first parameter is of type (optionally cv-qualified) X and
6232 // either there are no other parameters or else all other
6233 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006234 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006235 ((Constructor->getNumParams() == 1) ||
6236 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006237 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6238 Constructor->getTemplateSpecializationKind()
6239 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006240 QualType ParamType = Constructor->getParamDecl(0)->getType();
6241 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6242 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006243 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006244 const char *ConstRef
6245 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6246 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006247 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006248 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006249
6250 // FIXME: Rather that making the constructor invalid, we should endeavor
6251 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006252 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006253 }
6254 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006255}
6256
John McCalldeb646e2010-08-04 01:04:25 +00006257/// CheckDestructor - Checks a fully-formed destructor definition for
6258/// well-formedness, issuing any diagnostics required. Returns true
6259/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006260bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006261 CXXRecordDecl *RD = Destructor->getParent();
6262
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006263 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006264 SourceLocation Loc;
6265
6266 if (!Destructor->isImplicit())
6267 Loc = Destructor->getLocation();
6268 else
6269 Loc = RD->getLocation();
6270
6271 // If we have a virtual destructor, look up the deallocation function
6272 FunctionDecl *OperatorDelete = 0;
6273 DeclarationName Name =
6274 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006275 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006276 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006277 // If there's no class-specific operator delete, look up the global
6278 // non-array delete.
6279 if (!OperatorDelete)
6280 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006281
Eli Friedmanfa0df832012-02-02 03:46:19 +00006282 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006283
6284 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006285 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006286
6287 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006288}
6289
Mike Stump11289f42009-09-09 15:08:12 +00006290static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006291FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6292 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6293 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006294 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006295}
6296
Douglas Gregor831c93f2008-11-05 20:51:48 +00006297/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6298/// the well-formednes of the destructor declarator @p D with type @p
6299/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006300/// emit diagnostics and set the declarator to invalid. Even if this happens,
6301/// will be updated to reflect a well-formed type for the destructor and
6302/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006303QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006304 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006305 // C++ [class.dtor]p1:
6306 // [...] A typedef-name that names a class is a class-name
6307 // (7.1.3); however, a typedef-name that names a class shall not
6308 // be used as the identifier in the declarator for a destructor
6309 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006310 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006311 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006312 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006313 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006314 else if (const TemplateSpecializationType *TST =
6315 DeclaratorType->getAs<TemplateSpecializationType>())
6316 if (TST->isTypeAlias())
6317 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6318 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006319
6320 // C++ [class.dtor]p2:
6321 // A destructor is used to destroy objects of its class type. A
6322 // destructor takes no parameters, and no return type can be
6323 // specified for it (not even void). The address of a destructor
6324 // shall not be taken. A destructor shall not be static. A
6325 // destructor can be invoked for a const, volatile or const
6326 // volatile object. A destructor shall not be declared const,
6327 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006328 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006329 if (!D.isInvalidType())
6330 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6331 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006332 << SourceRange(D.getIdentifierLoc())
6333 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6334
John McCall8e7d6562010-08-26 03:08:43 +00006335 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006336 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006337 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006338 // Destructors don't have return types, but the parser will
6339 // happily parse something like:
6340 //
6341 // class X {
6342 // float ~X();
6343 // };
6344 //
6345 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006346 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6347 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6348 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006349 }
Mike Stump11289f42009-09-09 15:08:12 +00006350
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006351 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006352 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006353 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006354 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6355 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006356 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006357 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6358 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006359 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006360 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6361 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006362 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006363 }
6364
Douglas Gregordb9d6642011-01-26 05:01:58 +00006365 // C++0x [class.dtor]p2:
6366 // A destructor shall not be declared with a ref-qualifier.
6367 if (FTI.hasRefQualifier()) {
6368 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6369 << FTI.RefQualifierIsLValueRef
6370 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6371 D.setInvalidType();
6372 }
6373
Douglas Gregor831c93f2008-11-05 20:51:48 +00006374 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00006375 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006376 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6377
6378 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00006379 FTI.freeArgs();
6380 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006381 }
6382
Mike Stump11289f42009-09-09 15:08:12 +00006383 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006384 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006385 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006386 D.setInvalidType();
6387 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006388
6389 // Rebuild the function type "R" without any type qualifiers or
6390 // parameters (in case any of the errors above fired) and with
6391 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006392 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006393 if (!D.isInvalidType())
6394 return R;
6395
Douglas Gregor95755162010-07-01 05:10:53 +00006396 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006397 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6398 EPI.Variadic = false;
6399 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006400 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006401 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006402}
6403
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006404/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6405/// well-formednes of the conversion function declarator @p D with
6406/// type @p R. If there are any errors in the declarator, this routine
6407/// will emit diagnostics and return true. Otherwise, it will return
6408/// false. Either way, the type @p R will be updated to reflect a
6409/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006410void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006411 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006412 // C++ [class.conv.fct]p1:
6413 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006414 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006415 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006416 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006417 if (!D.isInvalidType())
6418 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006419 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6420 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006421 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006422 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006423 }
John McCall212fa2e2010-04-13 00:04:31 +00006424
6425 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6426
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006427 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006428 // Conversion functions don't have return types, but the parser will
6429 // happily parse something like:
6430 //
6431 // class X {
6432 // float operator bool();
6433 // };
6434 //
6435 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006436 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6437 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6438 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006439 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006440 }
6441
John McCall212fa2e2010-04-13 00:04:31 +00006442 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6443
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006444 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00006445 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006446 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6447
6448 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006449 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006450 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006451 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006452 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006453 D.setInvalidType();
6454 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006455
John McCall212fa2e2010-04-13 00:04:31 +00006456 // Diagnose "&operator bool()" and other such nonsense. This
6457 // is actually a gcc extension which we don't support.
6458 if (Proto->getResultType() != ConvType) {
6459 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6460 << Proto->getResultType();
6461 D.setInvalidType();
6462 ConvType = Proto->getResultType();
6463 }
6464
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006465 // C++ [class.conv.fct]p4:
6466 // The conversion-type-id shall not represent a function type nor
6467 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006468 if (ConvType->isArrayType()) {
6469 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6470 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006471 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006472 } else if (ConvType->isFunctionType()) {
6473 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6474 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006475 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006476 }
6477
6478 // Rebuild the function type "R" without any parameters (in case any
6479 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006480 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006481 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006482 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006483
Douglas Gregor5fb53972009-01-14 15:45:31 +00006484 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006485 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006486 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006487 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006488 diag::warn_cxx98_compat_explicit_conversion_functions :
6489 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006490 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006491}
6492
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006493/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6494/// the declaration of the given C++ conversion function. This routine
6495/// is responsible for recording the conversion function in the C++
6496/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006497Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006498 assert(Conversion && "Expected to receive a conversion function declaration");
6499
Douglas Gregor4287b372008-12-12 08:25:50 +00006500 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006501
6502 // Make sure we aren't redeclaring the conversion function.
6503 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006504
6505 // C++ [class.conv.fct]p1:
6506 // [...] A conversion function is never used to convert a
6507 // (possibly cv-qualified) object to the (possibly cv-qualified)
6508 // same object type (or a reference to it), to a (possibly
6509 // cv-qualified) base class of that type (or a reference to it),
6510 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006511 // FIXME: Suppress this warning if the conversion function ends up being a
6512 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006513 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006514 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006515 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006516 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006517 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6518 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006519 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006520 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006521 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6522 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006523 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006524 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006525 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006526 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006527 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006528 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006529 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006530 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006531 }
6532
Douglas Gregor457104e2010-09-29 04:25:11 +00006533 if (FunctionTemplateDecl *ConversionTemplate
6534 = Conversion->getDescribedFunctionTemplate())
6535 return ConversionTemplate;
6536
John McCall48871652010-08-21 09:40:31 +00006537 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006538}
6539
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006540//===----------------------------------------------------------------------===//
6541// Namespace Handling
6542//===----------------------------------------------------------------------===//
6543
Richard Smith45bb8852012-10-04 22:13:39 +00006544/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6545/// reopened.
6546static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6547 SourceLocation Loc,
6548 IdentifierInfo *II, bool *IsInline,
6549 NamespaceDecl *PrevNS) {
6550 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006551
Richard Smithf501cc32012-10-05 01:46:25 +00006552 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6553 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6554 // inline namespaces, with the intention of bringing names into namespace std.
6555 //
6556 // We support this just well enough to get that case working; this is not
6557 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006558 if (*IsInline && II && II->getName().startswith("__atomic") &&
6559 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006560 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006561 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6562 NS = NS->getPreviousDecl())
6563 NS->setInline(*IsInline);
6564 // Patch up the lookup table for the containing namespace. This isn't really
6565 // correct, but it's good enough for this particular case.
6566 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6567 E = PrevNS->decls_end(); I != E; ++I)
6568 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6569 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6570 return;
6571 }
6572
6573 if (PrevNS->isInline())
6574 // The user probably just forgot the 'inline', so suggest that it
6575 // be added back.
6576 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6577 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6578 else
6579 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6580 << IsInline;
6581
6582 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6583 *IsInline = PrevNS->isInline();
6584}
John McCallb1be5232010-08-26 09:15:37 +00006585
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006586/// ActOnStartNamespaceDef - This is called at the start of a namespace
6587/// definition.
John McCall48871652010-08-21 09:40:31 +00006588Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006589 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006590 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006591 SourceLocation IdentLoc,
6592 IdentifierInfo *II,
6593 SourceLocation LBrace,
6594 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006595 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6596 // For anonymous namespace, take the location of the left brace.
6597 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006598 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006599 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006600 bool IsStd = false;
6601 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006602 Scope *DeclRegionScope = NamespcScope->getParent();
6603
Douglas Gregore57e7522012-01-07 09:11:48 +00006604 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006605 if (II) {
6606 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006607 // The identifier in an original-namespace-definition shall not
6608 // have been previously defined in the declarative region in
6609 // which the original-namespace-definition appears. The
6610 // identifier in an original-namespace-definition is the name of
6611 // the namespace. Subsequently in that declarative region, it is
6612 // treated as an original-namespace-name.
6613 //
6614 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006615 // look through using directives, just look for any ordinary names.
6616
6617 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006618 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6619 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006620 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006621 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6622 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6623 ++I) {
6624 if ((*I)->getIdentifierNamespace() & IDNS) {
6625 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006626 break;
6627 }
6628 }
6629
Douglas Gregore57e7522012-01-07 09:11:48 +00006630 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6631
6632 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006633 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006634 if (IsInline != PrevNS->isInline())
6635 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6636 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006637 } else if (PrevDecl) {
6638 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006639 Diag(Loc, diag::err_redefinition_different_kind)
6640 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006641 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006642 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006643 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006644 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006645 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006646 // This is the first "real" definition of the namespace "std", so update
6647 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006648 PrevNS = getStdNamespace();
6649 IsStd = true;
6650 AddToKnown = !IsInline;
6651 } else {
6652 // We've seen this namespace for the first time.
6653 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006654 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006655 } else {
John McCall4fa53422009-10-01 00:25:31 +00006656 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006657
6658 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006659 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006660 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006661 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006662 } else {
6663 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006664 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006665 }
6666
Richard Smith45bb8852012-10-04 22:13:39 +00006667 if (PrevNS && IsInline != PrevNS->isInline())
6668 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6669 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006670 }
6671
6672 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6673 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006674 if (IsInvalid)
6675 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006676
6677 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006678
Douglas Gregore57e7522012-01-07 09:11:48 +00006679 // FIXME: Should we be merging attributes?
6680 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006681 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006682
6683 if (IsStd)
6684 StdNamespace = Namespc;
6685 if (AddToKnown)
6686 KnownNamespaces[Namespc] = false;
6687
6688 if (II) {
6689 PushOnScopeChains(Namespc, DeclRegionScope);
6690 } else {
6691 // Link the anonymous namespace into its parent.
6692 DeclContext *Parent = CurContext->getRedeclContext();
6693 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6694 TU->setAnonymousNamespace(Namespc);
6695 } else {
6696 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006697 }
John McCall4fa53422009-10-01 00:25:31 +00006698
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006699 CurContext->addDecl(Namespc);
6700
John McCall4fa53422009-10-01 00:25:31 +00006701 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6702 // behaves as if it were replaced by
6703 // namespace unique { /* empty body */ }
6704 // using namespace unique;
6705 // namespace unique { namespace-body }
6706 // where all occurrences of 'unique' in a translation unit are
6707 // replaced by the same identifier and this identifier differs
6708 // from all other identifiers in the entire program.
6709
6710 // We just create the namespace with an empty name and then add an
6711 // implicit using declaration, just like the standard suggests.
6712 //
6713 // CodeGen enforces the "universally unique" aspect by giving all
6714 // declarations semantically contained within an anonymous
6715 // namespace internal linkage.
6716
Douglas Gregore57e7522012-01-07 09:11:48 +00006717 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006718 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006719 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006720 /* 'using' */ LBrace,
6721 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006722 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006723 /* identifier */ SourceLocation(),
6724 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006725 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006726 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006727 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006728 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006729 }
6730
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006731 ActOnDocumentableDecl(Namespc);
6732
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006733 // Although we could have an invalid decl (i.e. the namespace name is a
6734 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006735 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6736 // for the namespace has the declarations that showed up in that particular
6737 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006738 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006739 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006740}
6741
Sebastian Redla6602e92009-11-23 15:34:23 +00006742/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6743/// is a namespace alias, returns the namespace it points to.
6744static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6745 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6746 return AD->getNamespace();
6747 return dyn_cast_or_null<NamespaceDecl>(D);
6748}
6749
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006750/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6751/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006752void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006753 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6754 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006755 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006756 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006757 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006758 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006759}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006760
John McCall28a0cf72010-08-25 07:42:41 +00006761CXXRecordDecl *Sema::getStdBadAlloc() const {
6762 return cast_or_null<CXXRecordDecl>(
6763 StdBadAlloc.get(Context.getExternalSource()));
6764}
6765
6766NamespaceDecl *Sema::getStdNamespace() const {
6767 return cast_or_null<NamespaceDecl>(
6768 StdNamespace.get(Context.getExternalSource()));
6769}
6770
Douglas Gregorcdf87022010-06-29 17:53:46 +00006771/// \brief Retrieve the special "std" namespace, which may require us to
6772/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006773NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006774 if (!StdNamespace) {
6775 // The "std" namespace has not yet been defined, so build one implicitly.
6776 StdNamespace = NamespaceDecl::Create(Context,
6777 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006778 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006779 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006780 &PP.getIdentifierTable().get("std"),
6781 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006782 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006783 }
6784
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006785 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006786}
6787
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006788bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006789 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006790 "Looking for std::initializer_list outside of C++.");
6791
6792 // We're looking for implicit instantiations of
6793 // template <typename E> class std::initializer_list.
6794
6795 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6796 return false;
6797
Sebastian Redl43144e72012-01-17 22:49:58 +00006798 ClassTemplateDecl *Template = 0;
6799 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006800
Sebastian Redl43144e72012-01-17 22:49:58 +00006801 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006802
Sebastian Redl43144e72012-01-17 22:49:58 +00006803 ClassTemplateSpecializationDecl *Specialization =
6804 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6805 if (!Specialization)
6806 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006807
Sebastian Redl43144e72012-01-17 22:49:58 +00006808 Template = Specialization->getSpecializedTemplate();
6809 Arguments = Specialization->getTemplateArgs().data();
6810 } else if (const TemplateSpecializationType *TST =
6811 Ty->getAs<TemplateSpecializationType>()) {
6812 Template = dyn_cast_or_null<ClassTemplateDecl>(
6813 TST->getTemplateName().getAsTemplateDecl());
6814 Arguments = TST->getArgs();
6815 }
6816 if (!Template)
6817 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006818
6819 if (!StdInitializerList) {
6820 // Haven't recognized std::initializer_list yet, maybe this is it.
6821 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6822 if (TemplateClass->getIdentifier() !=
6823 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006824 !getStdNamespace()->InEnclosingNamespaceSetOf(
6825 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006826 return false;
6827 // This is a template called std::initializer_list, but is it the right
6828 // template?
6829 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006830 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006831 return false;
6832 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6833 return false;
6834
6835 // It's the right template.
6836 StdInitializerList = Template;
6837 }
6838
6839 if (Template != StdInitializerList)
6840 return false;
6841
6842 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006843 if (Element)
6844 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006845 return true;
6846}
6847
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006848static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6849 NamespaceDecl *Std = S.getStdNamespace();
6850 if (!Std) {
6851 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6852 return 0;
6853 }
6854
6855 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6856 Loc, Sema::LookupOrdinaryName);
6857 if (!S.LookupQualifiedName(Result, Std)) {
6858 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6859 return 0;
6860 }
6861 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6862 if (!Template) {
6863 Result.suppressDiagnostics();
6864 // We found something weird. Complain about the first thing we found.
6865 NamedDecl *Found = *Result.begin();
6866 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6867 return 0;
6868 }
6869
6870 // We found some template called std::initializer_list. Now verify that it's
6871 // correct.
6872 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006873 if (Params->getMinRequiredArguments() != 1 ||
6874 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006875 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6876 return 0;
6877 }
6878
6879 return Template;
6880}
6881
6882QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6883 if (!StdInitializerList) {
6884 StdInitializerList = LookupStdInitializerList(*this, Loc);
6885 if (!StdInitializerList)
6886 return QualType();
6887 }
6888
6889 TemplateArgumentListInfo Args(Loc, Loc);
6890 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6891 Context.getTrivialTypeSourceInfo(Element,
6892 Loc)));
6893 return Context.getCanonicalType(
6894 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6895}
6896
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006897bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6898 // C++ [dcl.init.list]p2:
6899 // A constructor is an initializer-list constructor if its first parameter
6900 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6901 // std::initializer_list<E> for some type E, and either there are no other
6902 // parameters or else all other parameters have default arguments.
6903 if (Ctor->getNumParams() < 1 ||
6904 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6905 return false;
6906
6907 QualType ArgType = Ctor->getParamDecl(0)->getType();
6908 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6909 ArgType = RT->getPointeeType().getUnqualifiedType();
6910
6911 return isStdInitializerList(ArgType, 0);
6912}
6913
Douglas Gregora172e082011-03-26 22:25:30 +00006914/// \brief Determine whether a using statement is in a context where it will be
6915/// apply in all contexts.
6916static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6917 switch (CurContext->getDeclKind()) {
6918 case Decl::TranslationUnit:
6919 return true;
6920 case Decl::LinkageSpec:
6921 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6922 default:
6923 return false;
6924 }
6925}
6926
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006927namespace {
6928
6929// Callback to only accept typo corrections that are namespaces.
6930class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006931public:
6932 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6933 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006934 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006935 return false;
6936 }
6937};
6938
6939}
6940
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006941static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6942 CXXScopeSpec &SS,
6943 SourceLocation IdentLoc,
6944 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006945 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006946 R.clear();
6947 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006948 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006949 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006950 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006951 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6952 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006953 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006954 S.diagnoseTypo(Corrected,
6955 S.PDiag(diag::err_using_directive_member_suggest)
6956 << Ident << DC << DroppedSpecifier << SS.getRange(),
6957 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006958 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006959 S.diagnoseTypo(Corrected,
6960 S.PDiag(diag::err_using_directive_suggest) << Ident,
6961 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006962 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006963 R.addDecl(Corrected.getCorrectionDecl());
6964 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006965 }
6966 return false;
6967}
6968
John McCall48871652010-08-21 09:40:31 +00006969Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006970 SourceLocation UsingLoc,
6971 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006972 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006973 SourceLocation IdentLoc,
6974 IdentifierInfo *NamespcName,
6975 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006976 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6977 assert(NamespcName && "Invalid NamespcName.");
6978 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006979
6980 // This can only happen along a recovery path.
6981 while (S->getFlags() & Scope::TemplateParamScope)
6982 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006983 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006984
Douglas Gregor889ceb72009-02-03 19:21:40 +00006985 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006986 NestedNameSpecifier *Qualifier = 0;
6987 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006988 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006989
Douglas Gregor34074322009-01-14 22:20:51 +00006990 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006991 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6992 LookupParsedName(R, S, &SS);
6993 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006994 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006995
Douglas Gregorcdf87022010-06-29 17:53:46 +00006996 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006997 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006998 // Allow "using namespace std;" or "using namespace ::std;" even if
6999 // "std" hasn't been defined yet, for GCC compatibility.
7000 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7001 NamespcName->isStr("std")) {
7002 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007003 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007004 R.resolveKind();
7005 }
7006 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007007 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007008 }
7009
John McCall9f3059a2009-10-09 21:13:30 +00007010 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007011 NamedDecl *Named = R.getFoundDecl();
7012 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7013 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007014 // C++ [namespace.udir]p1:
7015 // A using-directive specifies that the names in the nominated
7016 // namespace can be used in the scope in which the
7017 // using-directive appears after the using-directive. During
7018 // unqualified name lookup (3.4.1), the names appear as if they
7019 // were declared in the nearest enclosing namespace which
7020 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007021 // namespace. [Note: in this context, "contains" means "contains
7022 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007023
7024 // Find enclosing context containing both using-directive and
7025 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007026 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007027 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7028 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7029 CommonAncestor = CommonAncestor->getParent();
7030
Sebastian Redla6602e92009-11-23 15:34:23 +00007031 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007032 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007033 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007034
Douglas Gregora172e082011-03-26 22:25:30 +00007035 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007036 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007037 Diag(IdentLoc, diag::warn_using_directive_in_header);
7038 }
7039
Douglas Gregor889ceb72009-02-03 19:21:40 +00007040 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007041 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007042 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007043 }
7044
Richard Smith54ecd982013-02-20 19:22:51 +00007045 if (UDir)
7046 ProcessDeclAttributeList(S, UDir, AttrList);
7047
John McCall48871652010-08-21 09:40:31 +00007048 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007049}
7050
7051void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007052 // If the scope has an associated entity and the using directive is at
7053 // namespace or translation unit scope, add the UsingDirectiveDecl into
7054 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007055 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007056 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007057 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007058 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007059 // Otherwise, it is at block sope. The using-directives will affect lookup
7060 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007061 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007062}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007063
Douglas Gregorfec52632009-06-20 00:51:54 +00007064
John McCall48871652010-08-21 09:40:31 +00007065Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007066 AccessSpecifier AS,
7067 bool HasUsingKeyword,
7068 SourceLocation UsingLoc,
7069 CXXScopeSpec &SS,
7070 UnqualifiedId &Name,
7071 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007072 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007073 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007074 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007075
Douglas Gregor220f4272009-11-04 16:30:06 +00007076 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007077 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007078 case UnqualifiedId::IK_Identifier:
7079 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007080 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007081 case UnqualifiedId::IK_ConversionFunctionId:
7082 break;
7083
7084 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007085 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007086 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007087 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007088 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007089 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007090 diag::err_using_decl_constructor)
7091 << SS.getRange();
7092
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007093 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007094
John McCall48871652010-08-21 09:40:31 +00007095 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007096
7097 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007098 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007099 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007100 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007101
7102 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007103 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007104 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007105 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007106 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007107
7108 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7109 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007110 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007111 return 0;
John McCall3969e302009-12-08 07:46:18 +00007112
Richard Smithc2bc61b2013-03-18 21:12:30 +00007113 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007114 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007115 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007116 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7117 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007118 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007119 }
7120
Douglas Gregorc4356532010-12-16 00:46:58 +00007121 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7122 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7123 return 0;
7124
John McCall3f746822009-11-17 05:59:44 +00007125 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007126 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007127 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007128 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007129 if (UD)
7130 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007131
John McCall48871652010-08-21 09:40:31 +00007132 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007133}
7134
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007135/// \brief Determine whether a using declaration considers the given
7136/// declarations as "equivalent", e.g., if they are redeclarations of
7137/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007138static bool
7139IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7140 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007141 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007142
Richard Smithdda56e42011-04-15 14:24:37 +00007143 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007144 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007145 return Context.hasSameType(TD1->getUnderlyingType(),
7146 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007147
7148 return false;
7149}
7150
7151
John McCall84d87672009-12-10 09:41:52 +00007152/// Determines whether to create a using shadow decl for a particular
7153/// decl, given the set of decls existing prior to this using lookup.
7154bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007155 const LookupResult &Previous,
7156 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007157 // Diagnose finding a decl which is not from a base class of the
7158 // current class. We do this now because there are cases where this
7159 // function will silently decide not to build a shadow decl, which
7160 // will pre-empt further diagnostics.
7161 //
7162 // We don't need to do this in C++0x because we do the check once on
7163 // the qualifier.
7164 //
7165 // FIXME: diagnose the following if we care enough:
7166 // struct A { int foo; };
7167 // struct B : A { using A::foo; };
7168 // template <class T> struct C : A {};
7169 // template <class T> struct D : C<T> { using B::foo; } // <---
7170 // This is invalid (during instantiation) in C++03 because B::foo
7171 // resolves to the using decl in B, which is not a base class of D<T>.
7172 // We can't diagnose it immediately because C<T> is an unknown
7173 // specialization. The UsingShadowDecl in D<T> then points directly
7174 // to A::foo, which will look well-formed when we instantiate.
7175 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007176 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007177 DeclContext *OrigDC = Orig->getDeclContext();
7178
7179 // Handle enums and anonymous structs.
7180 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7181 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7182 while (OrigRec->isAnonymousStructOrUnion())
7183 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7184
7185 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7186 if (OrigDC == CurContext) {
7187 Diag(Using->getLocation(),
7188 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007189 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007190 Diag(Orig->getLocation(), diag::note_using_decl_target);
7191 return true;
7192 }
7193
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007194 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007195 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007196 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007197 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007198 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007199 Diag(Orig->getLocation(), diag::note_using_decl_target);
7200 return true;
7201 }
7202 }
7203
7204 if (Previous.empty()) return false;
7205
7206 NamedDecl *Target = Orig;
7207 if (isa<UsingShadowDecl>(Target))
7208 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7209
John McCalla17e83e2009-12-11 02:33:26 +00007210 // If the target happens to be one of the previous declarations, we
7211 // don't have a conflict.
7212 //
7213 // FIXME: but we might be increasing its access, in which case we
7214 // should redeclare it.
7215 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007216 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007217 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7218 I != E; ++I) {
7219 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007220 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7221 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7222 PrevShadow = Shadow;
7223 FoundEquivalentDecl = true;
7224 }
John McCalla17e83e2009-12-11 02:33:26 +00007225
7226 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7227 }
7228
Richard Smithfd8634a2013-10-23 02:17:46 +00007229 if (FoundEquivalentDecl)
7230 return false;
7231
John McCall84d87672009-12-10 09:41:52 +00007232 if (Target->isFunctionOrFunctionTemplate()) {
7233 FunctionDecl *FD;
7234 if (isa<FunctionTemplateDecl>(Target))
7235 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7236 else
7237 FD = cast<FunctionDecl>(Target);
7238
7239 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007240 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007241 case Ovl_Overload:
7242 return false;
7243
7244 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007245 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007246 break;
7247
7248 // We found a decl with the exact signature.
7249 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007250 // If we're in a record, we want to hide the target, so we
7251 // return true (without a diagnostic) to tell the caller not to
7252 // build a shadow decl.
7253 if (CurContext->isRecord())
7254 return true;
7255
7256 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007257 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007258 break;
7259 }
7260
7261 Diag(Target->getLocation(), diag::note_using_decl_target);
7262 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7263 return true;
7264 }
7265
7266 // Target is not a function.
7267
John McCall84d87672009-12-10 09:41:52 +00007268 if (isa<TagDecl>(Target)) {
7269 // No conflict between a tag and a non-tag.
7270 if (!Tag) return false;
7271
John McCalle29c5cd2009-12-10 19:51:03 +00007272 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007273 Diag(Target->getLocation(), diag::note_using_decl_target);
7274 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7275 return true;
7276 }
7277
7278 // No conflict between a tag and a non-tag.
7279 if (!NonTag) return false;
7280
John McCalle29c5cd2009-12-10 19:51:03 +00007281 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007282 Diag(Target->getLocation(), diag::note_using_decl_target);
7283 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7284 return true;
7285}
7286
John McCall3f746822009-11-17 05:59:44 +00007287/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007288UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007289 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007290 NamedDecl *Orig,
7291 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007292
7293 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007294 NamedDecl *Target = Orig;
7295 if (isa<UsingShadowDecl>(Target)) {
7296 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7297 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007298 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007299
John McCall3f746822009-11-17 05:59:44 +00007300 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007301 = UsingShadowDecl::Create(Context, CurContext,
7302 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007303 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007304
Douglas Gregor457104e2010-09-29 04:25:11 +00007305 Shadow->setAccess(UD->getAccess());
7306 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7307 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007308
7309 Shadow->setPreviousDecl(PrevDecl);
7310
John McCall3f746822009-11-17 05:59:44 +00007311 if (S)
John McCall3969e302009-12-08 07:46:18 +00007312 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007313 else
John McCall3969e302009-12-08 07:46:18 +00007314 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007315
John McCall3969e302009-12-08 07:46:18 +00007316
John McCall84d87672009-12-10 09:41:52 +00007317 return Shadow;
7318}
John McCall3969e302009-12-08 07:46:18 +00007319
John McCall84d87672009-12-10 09:41:52 +00007320/// Hides a using shadow declaration. This is required by the current
7321/// using-decl implementation when a resolvable using declaration in a
7322/// class is followed by a declaration which would hide or override
7323/// one or more of the using decl's targets; for example:
7324///
7325/// struct Base { void foo(int); };
7326/// struct Derived : Base {
7327/// using Base::foo;
7328/// void foo(int);
7329/// };
7330///
7331/// The governing language is C++03 [namespace.udecl]p12:
7332///
7333/// When a using-declaration brings names from a base class into a
7334/// derived class scope, member functions in the derived class
7335/// override and/or hide member functions with the same name and
7336/// parameter types in a base class (rather than conflicting).
7337///
7338/// There are two ways to implement this:
7339/// (1) optimistically create shadow decls when they're not hidden
7340/// by existing declarations, or
7341/// (2) don't create any shadow decls (or at least don't make them
7342/// visible) until we've fully parsed/instantiated the class.
7343/// The problem with (1) is that we might have to retroactively remove
7344/// a shadow decl, which requires several O(n) operations because the
7345/// decl structures are (very reasonably) not designed for removal.
7346/// (2) avoids this but is very fiddly and phase-dependent.
7347void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007348 if (Shadow->getDeclName().getNameKind() ==
7349 DeclarationName::CXXConversionFunctionName)
7350 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7351
John McCall84d87672009-12-10 09:41:52 +00007352 // Remove it from the DeclContext...
7353 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007354
John McCall84d87672009-12-10 09:41:52 +00007355 // ...and the scope, if applicable...
7356 if (S) {
John McCall48871652010-08-21 09:40:31 +00007357 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007358 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007359 }
7360
John McCall84d87672009-12-10 09:41:52 +00007361 // ...and the using decl.
7362 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7363
7364 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007365 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007366}
7367
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007368namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007369class UsingValidatorCCC : public CorrectionCandidateCallback {
7370public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007371 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7372 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007373 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007374 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007375
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007376 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7377 NamedDecl *ND = Candidate.getCorrectionDecl();
7378
7379 // Keywords are not valid here.
7380 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007381 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007382
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007383 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7384 !isa<TypeDecl>(ND))
7385 return false;
7386
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007387 // Completely unqualified names are invalid for a 'using' declaration.
7388 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7389 return false;
7390
7391 if (isa<TypeDecl>(ND))
7392 return HasTypenameKeyword || !IsInstantiation;
7393
7394 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007395 }
7396
7397private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007398 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007399 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007400 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007401};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007402} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007403
John McCalle61f2ba2009-11-18 02:36:19 +00007404/// Builds a using declaration.
7405///
7406/// \param IsInstantiation - Whether this call arises from an
7407/// instantiation of an unresolved using declaration. We treat
7408/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007409NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7410 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007411 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007412 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007413 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007414 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007415 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007416 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007417 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007418 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007419 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007420
Anders Carlssonf038fc22009-08-28 05:49:21 +00007421 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007422
Anders Carlsson59140b32009-08-28 03:16:11 +00007423 if (SS.isEmpty()) {
7424 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007425 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007426 }
Mike Stump11289f42009-09-09 15:08:12 +00007427
John McCall84d87672009-12-10 09:41:52 +00007428 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007429 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007430 ForRedeclaration);
7431 Previous.setHideTags(false);
7432 if (S) {
7433 LookupName(Previous, S);
7434
7435 // It is really dumb that we have to do this.
7436 LookupResult::Filter F = Previous.makeFilter();
7437 while (F.hasNext()) {
7438 NamedDecl *D = F.next();
7439 if (!isDeclInScope(D, CurContext, S))
7440 F.erase();
7441 }
7442 F.done();
7443 } else {
7444 assert(IsInstantiation && "no scope in non-instantiation");
7445 assert(CurContext->isRecord() && "scope not record in instantiation");
7446 LookupQualifiedName(Previous, CurContext);
7447 }
7448
John McCall84d87672009-12-10 09:41:52 +00007449 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007450 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7451 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007452 return 0;
7453
7454 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007455 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7456 return 0;
7457
John McCall84c16cf2009-11-12 03:15:40 +00007458 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007459 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007460 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007461 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007462 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007463 // FIXME: not all declaration name kinds are legal here
7464 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7465 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007466 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007467 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007468 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007469 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7470 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007471 }
John McCallb96ec562009-12-04 22:46:56 +00007472 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007473 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007474 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007475 }
John McCallb96ec562009-12-04 22:46:56 +00007476 D->setAccess(AS);
7477 CurContext->addDecl(D);
7478
7479 if (!LookupContext) return D;
7480 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007481
John McCall0b66eb32010-05-01 00:40:08 +00007482 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007483 UD->setInvalidDecl();
7484 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007485 }
7486
Richard Smith23d55872012-04-02 01:30:27 +00007487 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007488 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007489 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007490 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007491 return UD;
7492 }
7493
7494 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007495
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007496 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007497
John McCall3969e302009-12-08 07:46:18 +00007498 // Unlike most lookups, we don't always want to hide tag
7499 // declarations: tag names are visible through the using declaration
7500 // even if hidden by ordinary names, *except* in a dependent context
7501 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007502 if (!IsInstantiation)
7503 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007504
John McCall5dadb652012-04-07 03:04:20 +00007505 // For the purposes of this lookup, we have a base object type
7506 // equal to that of the current context.
7507 if (CurContext->isRecord()) {
7508 R.setBaseObjectType(
7509 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7510 }
7511
John McCall27b18f82009-11-17 02:14:36 +00007512 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007513
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007514 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007515 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007516 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7517 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007518 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7519 R.getLookupKind(), S, &SS, CCC)){
7520 // We reject any correction for which ND would be NULL.
7521 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007522 R.setLookupName(Corrected.getCorrection());
7523 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007524 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007525 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007526 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7527 << NameInfo.getName() << LookupContext << 0
7528 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007529 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007530 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007531 << NameInfo.getName() << LookupContext << SS.getRange();
7532 UD->setInvalidDecl();
7533 return UD;
7534 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007535 }
7536
John McCallb96ec562009-12-04 22:46:56 +00007537 if (R.isAmbiguous()) {
7538 UD->setInvalidDecl();
7539 return UD;
7540 }
Mike Stump11289f42009-09-09 15:08:12 +00007541
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007542 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007543 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007544 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007545 Diag(IdentLoc, diag::err_using_typename_non_type);
7546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7547 Diag((*I)->getUnderlyingDecl()->getLocation(),
7548 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007549 UD->setInvalidDecl();
7550 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007551 }
7552 } else {
7553 // If we asked for a non-typename and we got a type, error out,
7554 // but only if this is an instantiation of an unresolved using
7555 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007556 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007557 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7558 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007559 UD->setInvalidDecl();
7560 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007561 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007562 }
7563
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007564 // C++0x N2914 [namespace.udecl]p6:
7565 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007566 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007567 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7568 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007569 UD->setInvalidDecl();
7570 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007571 }
Mike Stump11289f42009-09-09 15:08:12 +00007572
John McCall84d87672009-12-10 09:41:52 +00007573 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007574 UsingShadowDecl *PrevDecl = 0;
7575 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7576 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007577 }
John McCall3f746822009-11-17 05:59:44 +00007578
7579 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007580}
7581
Sebastian Redl08905022011-02-05 19:23:19 +00007582/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007583bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007584 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007585
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007586 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007587 assert(SourceType &&
7588 "Using decl naming constructor doesn't have type in scope spec.");
7589 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7590
7591 // Check whether the named type is a direct base class.
7592 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7593 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7594 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7595 BaseIt != BaseE; ++BaseIt) {
7596 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7597 if (CanonicalSourceType == BaseType)
7598 break;
Richard Smith23d55872012-04-02 01:30:27 +00007599 if (BaseIt->getType()->isDependentType())
7600 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007601 }
7602
7603 if (BaseIt == BaseE) {
7604 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007605 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007606 diag::err_using_decl_constructor_not_in_direct_base)
7607 << UD->getNameInfo().getSourceRange()
7608 << QualType(SourceType, 0) << TargetClass;
7609 return true;
7610 }
7611
Richard Smith23d55872012-04-02 01:30:27 +00007612 if (!CurContext->isDependentContext())
7613 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007614
7615 return false;
7616}
7617
John McCall84d87672009-12-10 09:41:52 +00007618/// Checks that the given using declaration is not an invalid
7619/// redeclaration. Note that this is checking only for the using decl
7620/// itself, not for any ill-formedness among the UsingShadowDecls.
7621bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007622 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007623 const CXXScopeSpec &SS,
7624 SourceLocation NameLoc,
7625 const LookupResult &Prev) {
7626 // C++03 [namespace.udecl]p8:
7627 // C++0x [namespace.udecl]p10:
7628 // A using-declaration is a declaration and can therefore be used
7629 // repeatedly where (and only where) multiple declarations are
7630 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007631 //
John McCall032092f2010-11-29 18:01:58 +00007632 // That's in non-member contexts.
7633 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007634 return false;
7635
Aaron Ballman4a979672014-01-03 13:56:08 +00007636 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007637
7638 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7639 NamedDecl *D = *I;
7640
7641 bool DTypename;
7642 NestedNameSpecifier *DQual;
7643 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007644 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007645 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007646 } else if (UnresolvedUsingValueDecl *UD
7647 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7648 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007649 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007650 } else if (UnresolvedUsingTypenameDecl *UD
7651 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7652 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007653 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007654 } else continue;
7655
7656 // using decls differ if one says 'typename' and the other doesn't.
7657 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007658 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007659
7660 // using decls differ if they name different scopes (but note that
7661 // template instantiation can cause this check to trigger when it
7662 // didn't before instantiation).
7663 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7664 Context.getCanonicalNestedNameSpecifier(DQual))
7665 continue;
7666
7667 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007668 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007669 return true;
7670 }
7671
7672 return false;
7673}
7674
John McCall3969e302009-12-08 07:46:18 +00007675
John McCallb96ec562009-12-04 22:46:56 +00007676/// Checks that the given nested-name qualifier used in a using decl
7677/// in the current context is appropriately related to the current
7678/// scope. If an error is found, diagnoses it and returns true.
7679bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7680 const CXXScopeSpec &SS,
7681 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007682 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007683
John McCall3969e302009-12-08 07:46:18 +00007684 if (!CurContext->isRecord()) {
7685 // C++03 [namespace.udecl]p3:
7686 // C++0x [namespace.udecl]p8:
7687 // A using-declaration for a class member shall be a member-declaration.
7688
7689 // If we weren't able to compute a valid scope, it must be a
7690 // dependent class scope.
7691 if (!NamedContext || NamedContext->isRecord()) {
7692 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7693 << SS.getRange();
7694 return true;
7695 }
7696
7697 // Otherwise, everything is known to be fine.
7698 return false;
7699 }
7700
7701 // The current scope is a record.
7702
7703 // If the named context is dependent, we can't decide much.
7704 if (!NamedContext) {
7705 // FIXME: in C++0x, we can diagnose if we can prove that the
7706 // nested-name-specifier does not refer to a base class, which is
7707 // still possible in some cases.
7708
7709 // Otherwise we have to conservatively report that things might be
7710 // okay.
7711 return false;
7712 }
7713
7714 if (!NamedContext->isRecord()) {
7715 // Ideally this would point at the last name in the specifier,
7716 // but we don't have that level of source info.
7717 Diag(SS.getRange().getBegin(),
7718 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007719 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007720 return true;
7721 }
7722
Douglas Gregor7c842292010-12-21 07:41:49 +00007723 if (!NamedContext->isDependentContext() &&
7724 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7725 return true;
7726
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007727 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007728 // C++0x [namespace.udecl]p3:
7729 // In a using-declaration used as a member-declaration, the
7730 // nested-name-specifier shall name a base class of the class
7731 // being defined.
7732
7733 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7734 cast<CXXRecordDecl>(NamedContext))) {
7735 if (CurContext == NamedContext) {
7736 Diag(NameLoc,
7737 diag::err_using_decl_nested_name_specifier_is_current_class)
7738 << SS.getRange();
7739 return true;
7740 }
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 return true;
7748 }
7749
7750 return false;
7751 }
7752
7753 // C++03 [namespace.udecl]p4:
7754 // A using-declaration used as a member-declaration shall refer
7755 // to a member of a base class of the class being defined [etc.].
7756
7757 // Salient point: SS doesn't have to name a base class as long as
7758 // lookup only finds members from base classes. Therefore we can
7759 // diagnose here only if we can prove that that can't happen,
7760 // i.e. if the class hierarchies provably don't intersect.
7761
7762 // TODO: it would be nice if "definitely valid" results were cached
7763 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7764 // need to be repeated.
7765
7766 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007767 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007768
7769 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7770 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7771 Data->Bases.insert(Base);
7772 return true;
7773 }
7774
7775 bool hasDependentBases(const CXXRecordDecl *Class) {
7776 return !Class->forallBases(collect, this);
7777 }
7778
7779 /// Returns true if the base is dependent or is one of the
7780 /// accumulated base classes.
7781 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7782 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7783 return !Data->Bases.count(Base);
7784 }
7785
7786 bool mightShareBases(const CXXRecordDecl *Class) {
7787 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7788 }
7789 };
7790
7791 UserData Data;
7792
7793 // Returns false if we find a dependent base.
7794 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7795 return false;
7796
7797 // Returns false if the class has a dependent base or if it or one
7798 // of its bases is present in the base set of the current context.
7799 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7800 return false;
7801
7802 Diag(SS.getRange().getBegin(),
7803 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007804 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007805 << cast<CXXRecordDecl>(CurContext)
7806 << SS.getRange();
7807
7808 return true;
John McCallb96ec562009-12-04 22:46:56 +00007809}
7810
Richard Smithdda56e42011-04-15 14:24:37 +00007811Decl *Sema::ActOnAliasDeclaration(Scope *S,
7812 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007813 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007814 SourceLocation UsingLoc,
7815 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007816 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007817 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007818 // Skip up to the relevant declaration scope.
7819 while (S->getFlags() & Scope::TemplateParamScope)
7820 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007821 assert((S->getFlags() & Scope::DeclScope) &&
7822 "got alias-declaration outside of declaration scope");
7823
7824 if (Type.isInvalid())
7825 return 0;
7826
7827 bool Invalid = false;
7828 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7829 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007830 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007831
7832 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7833 return 0;
7834
7835 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007836 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007837 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007838 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7839 TInfo->getTypeLoc().getBeginLoc());
7840 }
Richard Smithdda56e42011-04-15 14:24:37 +00007841
7842 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7843 LookupName(Previous, S);
7844
7845 // Warn about shadowing the name of a template parameter.
7846 if (Previous.isSingleResult() &&
7847 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007848 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007849 Previous.clear();
7850 }
7851
7852 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7853 "name in alias declaration must be an identifier");
7854 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7855 Name.StartLocation,
7856 Name.Identifier, TInfo);
7857
7858 NewTD->setAccess(AS);
7859
7860 if (Invalid)
7861 NewTD->setInvalidDecl();
7862
Richard Smith54ecd982013-02-20 19:22:51 +00007863 ProcessDeclAttributeList(S, NewTD, AttrList);
7864
Richard Smith3f1b5d02011-05-05 21:57:07 +00007865 CheckTypedefForVariablyModifiedType(S, NewTD);
7866 Invalid |= NewTD->isInvalidDecl();
7867
Richard Smithdda56e42011-04-15 14:24:37 +00007868 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007869
7870 NamedDecl *NewND;
7871 if (TemplateParamLists.size()) {
7872 TypeAliasTemplateDecl *OldDecl = 0;
7873 TemplateParameterList *OldTemplateParams = 0;
7874
7875 if (TemplateParamLists.size() != 1) {
7876 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007877 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7878 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007879 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007880 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007881
7882 // Only consider previous declarations in the same scope.
7883 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7884 /*ExplicitInstantiationOrSpecialization*/false);
7885 if (!Previous.empty()) {
7886 Redeclaration = true;
7887
7888 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7889 if (!OldDecl && !Invalid) {
7890 Diag(UsingLoc, diag::err_redefinition_different_kind)
7891 << Name.Identifier;
7892
7893 NamedDecl *OldD = Previous.getRepresentativeDecl();
7894 if (OldD->getLocation().isValid())
7895 Diag(OldD->getLocation(), diag::note_previous_definition);
7896
7897 Invalid = true;
7898 }
7899
7900 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7901 if (TemplateParameterListsAreEqual(TemplateParams,
7902 OldDecl->getTemplateParameters(),
7903 /*Complain=*/true,
7904 TPL_TemplateMatch))
7905 OldTemplateParams = OldDecl->getTemplateParameters();
7906 else
7907 Invalid = true;
7908
7909 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7910 if (!Invalid &&
7911 !Context.hasSameType(OldTD->getUnderlyingType(),
7912 NewTD->getUnderlyingType())) {
7913 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7914 // but we can't reasonably accept it.
7915 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7916 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7917 if (OldTD->getLocation().isValid())
7918 Diag(OldTD->getLocation(), diag::note_previous_definition);
7919 Invalid = true;
7920 }
7921 }
7922 }
7923
7924 // Merge any previous default template arguments into our parameters,
7925 // and check the parameter list.
7926 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7927 TPC_TypeAliasTemplate))
7928 return 0;
7929
7930 TypeAliasTemplateDecl *NewDecl =
7931 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7932 Name.Identifier, TemplateParams,
7933 NewTD);
7934
7935 NewDecl->setAccess(AS);
7936
7937 if (Invalid)
7938 NewDecl->setInvalidDecl();
7939 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007940 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007941
7942 NewND = NewDecl;
7943 } else {
7944 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7945 NewND = NewTD;
7946 }
Richard Smithdda56e42011-04-15 14:24:37 +00007947
7948 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007949 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007950
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007951 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007952 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007953}
7954
John McCall48871652010-08-21 09:40:31 +00007955Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007956 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007957 SourceLocation AliasLoc,
7958 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007959 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007960 SourceLocation IdentLoc,
7961 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007962
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007963 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007964 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7965 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007966
Anders Carlssondca83c42009-03-28 06:23:46 +00007967 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007968 NamedDecl *PrevDecl
7969 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7970 ForRedeclaration);
7971 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7972 PrevDecl = 0;
7973
7974 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007975 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007976 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007977 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007978 // FIXME: At some point, we'll want to create the (redundant)
7979 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007980 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007981 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007982 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007983 }
Mike Stump11289f42009-09-09 15:08:12 +00007984
Anders Carlssondca83c42009-03-28 06:23:46 +00007985 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7986 diag::err_redefinition_different_kind;
7987 Diag(AliasLoc, DiagID) << Alias;
7988 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007989 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007990 }
7991
John McCall27b18f82009-11-17 02:14:36 +00007992 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007993 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007994
John McCall9f3059a2009-10-09 21:13:30 +00007995 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007996 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007997 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007998 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007999 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008000 }
Mike Stump11289f42009-09-09 15:08:12 +00008001
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008002 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008003 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008004 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008005 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008006
John McCalld8d0d432010-02-16 06:53:13 +00008007 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008008 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008009}
8010
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008011Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008012Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8013 CXXMethodDecl *MD) {
8014 CXXRecordDecl *ClassDecl = MD->getParent();
8015
Douglas Gregor6d880b12010-07-01 22:31:05 +00008016 // C++ [except.spec]p14:
8017 // An implicitly declared special member function (Clause 12) shall have an
8018 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008019 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008020 if (ClassDecl->isInvalidDecl())
8021 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008022
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008023 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008024 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8025 BEnd = ClassDecl->bases_end();
8026 B != BEnd; ++B) {
8027 if (B->isVirtual()) // Handled below.
8028 continue;
8029
Douglas Gregor9672f922010-07-03 00:47:00 +00008030 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8031 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008032 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8033 // If this is a deleted function, add it anyway. This might be conformant
8034 // with the standard. This might not. I'm not sure. It might not matter.
8035 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008036 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008037 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008038 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008039
8040 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008041 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8042 BEnd = ClassDecl->vbases_end();
8043 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008044 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008046 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8047 // If this is a deleted function, add it anyway. This might be conformant
8048 // with the standard. This might not. I'm not sure. It might not matter.
8049 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008050 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008051 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008052 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008053
8054 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008055 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8056 FEnd = ClassDecl->field_end();
8057 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00008058 if (F->hasInClassInitializer()) {
8059 if (Expr *E = F->getInClassInitializer())
8060 ExceptSpec.CalledExpr(E);
8061 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008062 // DR1351:
8063 // If the brace-or-equal-initializer of a non-static data member
8064 // invokes a defaulted default constructor of its class or of an
8065 // enclosing class in a potentially evaluated subexpression, the
8066 // program is ill-formed.
8067 //
8068 // This resolution is unworkable: the exception specification of the
8069 // default constructor can be needed in an unevaluated context, in
8070 // particular, in the operand of a noexcept-expression, and we can be
8071 // unable to compute an exception specification for an enclosed class.
8072 //
8073 // We do not allow an in-class initializer to require the evaluation
8074 // of the exception specification for any in-class initializer whose
8075 // definition is not lexically complete.
8076 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008077 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8081 // If this is a deleted function, add it anyway. This might be conformant
8082 // with the standard. This might not. I'm not sure. It might not matter.
8083 // In particular, the problem is that this function never gets called. It
8084 // might just be ill-formed because this function attempts to refer to
8085 // a deleted function here.
8086 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008087 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008088 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008089 }
John McCalldb40c7f2010-12-14 08:05:40 +00008090
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008091 return ExceptSpec;
8092}
8093
Richard Smithc2bc61b2013-03-18 21:12:30 +00008094Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008095Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8096 CXXRecordDecl *ClassDecl = CD->getParent();
8097
8098 // C++ [except.spec]p14:
8099 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008100 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008101 if (ClassDecl->isInvalidDecl())
8102 return ExceptSpec;
8103
8104 // Inherited constructor.
8105 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8106 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8107 // FIXME: Copying or moving the parameters could add extra exceptions to the
8108 // set, as could the default arguments for the inherited constructor. This
8109 // will be addressed when we implement the resolution of core issue 1351.
8110 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8111
8112 // Direct base-class constructors.
8113 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8114 BEnd = ClassDecl->bases_end();
8115 B != BEnd; ++B) {
8116 if (B->isVirtual()) // Handled below.
8117 continue;
8118
8119 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8120 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8121 if (BaseClassDecl == InheritedDecl)
8122 continue;
8123 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8124 if (Constructor)
8125 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8126 }
8127 }
8128
8129 // Virtual base-class constructors.
8130 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8131 BEnd = ClassDecl->vbases_end();
8132 B != BEnd; ++B) {
8133 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8134 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8135 if (BaseClassDecl == InheritedDecl)
8136 continue;
8137 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8138 if (Constructor)
8139 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8140 }
8141 }
8142
8143 // Field constructors.
8144 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8145 FEnd = ClassDecl->field_end();
8146 F != FEnd; ++F) {
8147 if (F->hasInClassInitializer()) {
8148 if (Expr *E = F->getInClassInitializer())
8149 ExceptSpec.CalledExpr(E);
8150 else if (!F->isInvalidDecl())
8151 Diag(CD->getLocation(),
8152 diag::err_in_class_initializer_references_def_ctor) << CD;
8153 } else if (const RecordType *RecordTy
8154 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8155 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8156 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8157 if (Constructor)
8158 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8159 }
8160 }
8161
Richard Smithc2bc61b2013-03-18 21:12:30 +00008162 return ExceptSpec;
8163}
8164
Richard Smith8bf22e52012-11-29 01:34:07 +00008165namespace {
8166/// RAII object to register a special member as being currently declared.
8167struct DeclaringSpecialMember {
8168 Sema &S;
8169 Sema::SpecialMemberDecl D;
8170 bool WasAlreadyBeingDeclared;
8171
8172 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8173 : S(S), D(RD, CSM) {
8174 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8175 if (WasAlreadyBeingDeclared)
8176 // This almost never happens, but if it does, ensure that our cache
8177 // doesn't contain a stale result.
8178 S.SpecialMemberCache.clear();
8179
8180 // FIXME: Register a note to be produced if we encounter an error while
8181 // declaring the special member.
8182 }
8183 ~DeclaringSpecialMember() {
8184 if (!WasAlreadyBeingDeclared)
8185 S.SpecialMembersBeingDeclared.erase(D);
8186 }
8187
8188 /// \brief Are we already trying to declare this special member?
8189 bool isAlreadyBeingDeclared() const {
8190 return WasAlreadyBeingDeclared;
8191 }
8192};
8193}
8194
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008195CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8196 CXXRecordDecl *ClassDecl) {
8197 // C++ [class.ctor]p5:
8198 // A default constructor for a class X is a constructor of class X
8199 // that can be called without an argument. If there is no
8200 // user-declared constructor for class X, a default constructor is
8201 // implicitly declared. An implicitly-declared default constructor
8202 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008203 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008204 "Should not build implicit default constructor!");
8205
Richard Smith8bf22e52012-11-29 01:34:07 +00008206 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8207 if (DSM.isAlreadyBeingDeclared())
8208 return 0;
8209
Richard Smithb5800092012-06-10 05:43:50 +00008210 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8211 CXXDefaultConstructor,
8212 false);
8213
Douglas Gregor6d880b12010-07-01 22:31:05 +00008214 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008215 CanQualType ClassType
8216 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008217 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008218 DeclarationName Name
8219 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008220 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008221 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008222 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008223 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008224 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008225 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008226 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008227 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008228
8229 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008230 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008231 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008232
Richard Smith6b02d462012-12-08 08:32:28 +00008233 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8234 // constructors is easy to compute.
8235 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8236
8237 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008238 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008239
Douglas Gregor9672f922010-07-03 00:47:00 +00008240 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008241 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008242
Douglas Gregor0be31a22010-07-02 17:43:08 +00008243 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008244 PushOnScopeChains(DefaultCon, S, false);
8245 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008246
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008247 return DefaultCon;
8248}
8249
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008250void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8251 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008252 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008253 !Constructor->doesThisDeclarationHaveABody() &&
8254 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008255 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008256
Anders Carlsson423f5d82010-04-23 16:04:08 +00008257 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008258 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008259
Eli Friedmaneaf34142012-10-18 20:14:08 +00008260 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008261 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008262 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008263 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008264 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008265 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008266 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008267 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008268 }
Douglas Gregor73193272010-09-20 16:48:21 +00008269
8270 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008271 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008272
Eli Friedman276dd182013-09-05 00:02:25 +00008273 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008274 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008275
8276 if (ASTMutationListener *L = getASTMutationListener()) {
8277 L->CompletedImplicitDefinition(Constructor);
8278 }
Richard Trieuef64e942013-10-25 00:56:00 +00008279
8280 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008281}
8282
Richard Smith938f40b2011-06-11 17:19:42 +00008283void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008284 // Perform any delayed checks on exception specifications.
8285 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008286}
8287
Richard Smith185be182013-04-10 05:48:59 +00008288namespace {
8289/// Information on inheriting constructors to declare.
8290class InheritingConstructorInfo {
8291public:
8292 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8293 : SemaRef(SemaRef), Derived(Derived) {
8294 // Mark the constructors that we already have in the derived class.
8295 //
8296 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8297 // unless there is a user-declared constructor with the same signature in
8298 // the class where the using-declaration appears.
8299 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8300 }
8301
8302 void inheritAll(CXXRecordDecl *RD) {
8303 visitAll(RD, &InheritingConstructorInfo::inherit);
8304 }
8305
8306private:
8307 /// Information about an inheriting constructor.
8308 struct InheritingConstructor {
8309 InheritingConstructor()
8310 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8311
8312 /// If \c true, a constructor with this signature is already declared
8313 /// in the derived class.
8314 bool DeclaredInDerived;
8315
8316 /// The constructor which is inherited.
8317 const CXXConstructorDecl *BaseCtor;
8318
8319 /// The derived constructor we declared.
8320 CXXConstructorDecl *DerivedCtor;
8321 };
8322
8323 /// Inheriting constructors with a given canonical type. There can be at
8324 /// most one such non-template constructor, and any number of templated
8325 /// constructors.
8326 struct InheritingConstructorsForType {
8327 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008328 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8329 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008330
8331 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8332 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8333 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8334 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8335 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8336 false, S.TPL_TemplateMatch))
8337 return Templates[I].second;
8338 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8339 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008340 }
Richard Smith185be182013-04-10 05:48:59 +00008341
8342 return NonTemplate;
8343 }
8344 };
8345
8346 /// Get or create the inheriting constructor record for a constructor.
8347 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8348 QualType CtorType) {
8349 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8350 .getEntry(SemaRef, Ctor);
8351 }
8352
8353 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8354
8355 /// Process all constructors for a class.
8356 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8357 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8358 CtorE = RD->ctor_end();
8359 CtorIt != CtorE; ++CtorIt)
8360 (this->*Callback)(*CtorIt);
8361 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8362 I(RD->decls_begin()), E(RD->decls_end());
8363 I != E; ++I) {
8364 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8365 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8366 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008367 }
8368 }
Richard Smith185be182013-04-10 05:48:59 +00008369
8370 /// Note that a constructor (or constructor template) was declared in Derived.
8371 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8372 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8373 }
8374
8375 /// Inherit a single constructor.
8376 void inherit(const CXXConstructorDecl *Ctor) {
8377 const FunctionProtoType *CtorType =
8378 Ctor->getType()->castAs<FunctionProtoType>();
8379 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8380 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8381
8382 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8383
8384 // Core issue (no number yet): the ellipsis is always discarded.
8385 if (EPI.Variadic) {
8386 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8387 SemaRef.Diag(Ctor->getLocation(),
8388 diag::note_using_decl_constructor_ellipsis);
8389 EPI.Variadic = false;
8390 }
8391
8392 // Declare a constructor for each number of parameters.
8393 //
8394 // C++11 [class.inhctor]p1:
8395 // The candidate set of inherited constructors from the class X named in
8396 // the using-declaration consists of [... modulo defects ...] for each
8397 // constructor or constructor template of X, the set of constructors or
8398 // constructor templates that results from omitting any ellipsis parameter
8399 // specification and successively omitting parameters with a default
8400 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008401 unsigned MinParams = minParamsToInherit(Ctor);
8402 unsigned Params = Ctor->getNumParams();
8403 if (Params >= MinParams) {
8404 do
8405 declareCtor(UsingLoc, Ctor,
8406 SemaRef.Context.getFunctionType(
8407 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8408 while (Params > MinParams &&
8409 Ctor->getParamDecl(--Params)->hasDefaultArg());
8410 }
Richard Smith185be182013-04-10 05:48:59 +00008411 }
8412
8413 /// Find the using-declaration which specified that we should inherit the
8414 /// constructors of \p Base.
8415 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8416 // No fancy lookup required; just look for the base constructor name
8417 // directly within the derived class.
8418 ASTContext &Context = SemaRef.Context;
8419 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8420 Context.getCanonicalType(Context.getRecordType(Base)));
8421 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8422 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8423 }
8424
8425 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8426 // C++11 [class.inhctor]p3:
8427 // [F]or each constructor template in the candidate set of inherited
8428 // constructors, a constructor template is implicitly declared
8429 if (Ctor->getDescribedFunctionTemplate())
8430 return 0;
8431
8432 // For each non-template constructor in the candidate set of inherited
8433 // constructors other than a constructor having no parameters or a
8434 // copy/move constructor having a single parameter, a constructor is
8435 // implicitly declared [...]
8436 if (Ctor->getNumParams() == 0)
8437 return 1;
8438 if (Ctor->isCopyOrMoveConstructor())
8439 return 2;
8440
8441 // Per discussion on core reflector, never inherit a constructor which
8442 // would become a default, copy, or move constructor of Derived either.
8443 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8444 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8445 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8446 }
8447
8448 /// Declare a single inheriting constructor, inheriting the specified
8449 /// constructor, with the given type.
8450 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8451 QualType DerivedType) {
8452 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8453
8454 // C++11 [class.inhctor]p3:
8455 // ... a constructor is implicitly declared with the same constructor
8456 // characteristics unless there is a user-declared constructor with
8457 // the same signature in the class where the using-declaration appears
8458 if (Entry.DeclaredInDerived)
8459 return;
8460
8461 // C++11 [class.inhctor]p7:
8462 // If two using-declarations declare inheriting constructors with the
8463 // same signature, the program is ill-formed
8464 if (Entry.DerivedCtor) {
8465 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8466 // Only diagnose this once per constructor.
8467 if (Entry.DerivedCtor->isInvalidDecl())
8468 return;
8469 Entry.DerivedCtor->setInvalidDecl();
8470
8471 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8472 SemaRef.Diag(BaseCtor->getLocation(),
8473 diag::note_using_decl_constructor_conflict_current_ctor);
8474 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8475 diag::note_using_decl_constructor_conflict_previous_ctor);
8476 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8477 diag::note_using_decl_constructor_conflict_previous_using);
8478 } else {
8479 // Core issue (no number): if the same inheriting constructor is
8480 // produced by multiple base class constructors from the same base
8481 // class, the inheriting constructor is defined as deleted.
8482 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8483 }
8484
8485 return;
8486 }
8487
8488 ASTContext &Context = SemaRef.Context;
8489 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8490 Context.getCanonicalType(Context.getRecordType(Derived)));
8491 DeclarationNameInfo NameInfo(Name, UsingLoc);
8492
8493 TemplateParameterList *TemplateParams = 0;
8494 if (const FunctionTemplateDecl *FTD =
8495 BaseCtor->getDescribedFunctionTemplate()) {
8496 TemplateParams = FTD->getTemplateParameters();
8497 // We're reusing template parameters from a different DeclContext. This
8498 // is questionable at best, but works out because the template depth in
8499 // both places is guaranteed to be 0.
8500 // FIXME: Rebuild the template parameters in the new context, and
8501 // transform the function type to refer to them.
8502 }
8503
8504 // Build type source info pointing at the using-declaration. This is
8505 // required by template instantiation.
8506 TypeSourceInfo *TInfo =
8507 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8508 FunctionProtoTypeLoc ProtoLoc =
8509 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8510
8511 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8512 Context, Derived, UsingLoc, NameInfo, DerivedType,
8513 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8514 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8515
8516 // Build an unevaluated exception specification for this constructor.
8517 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8518 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8519 EPI.ExceptionSpecType = EST_Unevaluated;
8520 EPI.ExceptionSpecDecl = DerivedCtor;
8521 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8522 FPT->getArgTypes(), EPI));
8523
8524 // Build the parameter declarations.
8525 SmallVector<ParmVarDecl *, 16> ParamDecls;
8526 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8527 TypeSourceInfo *TInfo =
8528 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8529 ParmVarDecl *PD = ParmVarDecl::Create(
8530 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8531 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8532 PD->setScopeInfo(0, I);
8533 PD->setImplicit();
8534 ParamDecls.push_back(PD);
8535 ProtoLoc.setArg(I, PD);
8536 }
8537
8538 // Set up the new constructor.
8539 DerivedCtor->setAccess(BaseCtor->getAccess());
8540 DerivedCtor->setParams(ParamDecls);
8541 DerivedCtor->setInheritedConstructor(BaseCtor);
8542 if (BaseCtor->isDeleted())
8543 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8544
8545 // If this is a constructor template, build the template declaration.
8546 if (TemplateParams) {
8547 FunctionTemplateDecl *DerivedTemplate =
8548 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8549 TemplateParams, DerivedCtor);
8550 DerivedTemplate->setAccess(BaseCtor->getAccess());
8551 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8552 Derived->addDecl(DerivedTemplate);
8553 } else {
8554 Derived->addDecl(DerivedCtor);
8555 }
8556
8557 Entry.BaseCtor = BaseCtor;
8558 Entry.DerivedCtor = DerivedCtor;
8559 }
8560
8561 Sema &SemaRef;
8562 CXXRecordDecl *Derived;
8563 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8564 MapType Map;
8565};
8566}
8567
8568void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8569 // Defer declaring the inheriting constructors until the class is
8570 // instantiated.
8571 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008572 return;
8573
Richard Smith185be182013-04-10 05:48:59 +00008574 // Find base classes from which we might inherit constructors.
8575 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8576 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8577 BaseE = ClassDecl->bases_end();
8578 BaseIt != BaseE; ++BaseIt)
8579 if (BaseIt->getInheritConstructors())
8580 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008581
Richard Smith185be182013-04-10 05:48:59 +00008582 // Go no further if we're not inheriting any constructors.
8583 if (InheritedBases.empty())
8584 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008585
Richard Smith185be182013-04-10 05:48:59 +00008586 // Declare the inherited constructors.
8587 InheritingConstructorInfo ICI(*this, ClassDecl);
8588 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8589 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008590}
8591
Richard Smithc2bc61b2013-03-18 21:12:30 +00008592void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8593 CXXConstructorDecl *Constructor) {
8594 CXXRecordDecl *ClassDecl = Constructor->getParent();
8595 assert(Constructor->getInheritedConstructor() &&
8596 !Constructor->doesThisDeclarationHaveABody() &&
8597 !Constructor->isDeleted());
8598
8599 SynthesizedFunctionScope Scope(*this, Constructor);
8600 DiagnosticErrorTrap Trap(Diags);
8601 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8602 Trap.hasErrorOccurred()) {
8603 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8604 << Context.getTagDeclType(ClassDecl);
8605 Constructor->setInvalidDecl();
8606 return;
8607 }
8608
8609 SourceLocation Loc = Constructor->getLocation();
8610 Constructor->setBody(new (Context) CompoundStmt(Loc));
8611
Eli Friedman276dd182013-09-05 00:02:25 +00008612 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008613 MarkVTableUsed(CurrentLocation, ClassDecl);
8614
8615 if (ASTMutationListener *L = getASTMutationListener()) {
8616 L->CompletedImplicitDefinition(Constructor);
8617 }
8618}
8619
8620
Alexis Huntf91729462011-05-12 22:46:25 +00008621Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008622Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8623 CXXRecordDecl *ClassDecl = MD->getParent();
8624
Douglas Gregorf1203042010-07-01 19:09:28 +00008625 // C++ [except.spec]p14:
8626 // An implicitly declared special member function (Clause 12) shall have
8627 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008628 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008629 if (ClassDecl->isInvalidDecl())
8630 return ExceptSpec;
8631
Douglas Gregorf1203042010-07-01 19:09:28 +00008632 // Direct base-class destructors.
8633 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8634 BEnd = ClassDecl->bases_end();
8635 B != BEnd; ++B) {
8636 if (B->isVirtual()) // Handled below.
8637 continue;
8638
8639 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008640 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008641 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008642 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008643
Douglas Gregorf1203042010-07-01 19:09:28 +00008644 // Virtual base-class destructors.
8645 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8646 BEnd = ClassDecl->vbases_end();
8647 B != BEnd; ++B) {
8648 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008649 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008650 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008651 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008652
Douglas Gregorf1203042010-07-01 19:09:28 +00008653 // Field destructors.
8654 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8655 FEnd = ClassDecl->field_end();
8656 F != FEnd; ++F) {
8657 if (const RecordType *RecordTy
8658 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008659 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008660 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008661 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008662
Alexis Huntf91729462011-05-12 22:46:25 +00008663 return ExceptSpec;
8664}
8665
8666CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8667 // C++ [class.dtor]p2:
8668 // If a class has no user-declared destructor, a destructor is
8669 // declared implicitly. An implicitly-declared destructor is an
8670 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008671 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008672
Richard Smith8bf22e52012-11-29 01:34:07 +00008673 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8674 if (DSM.isAlreadyBeingDeclared())
8675 return 0;
8676
Douglas Gregor7454c562010-07-02 20:37:36 +00008677 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008678 CanQualType ClassType
8679 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008680 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008681 DeclarationName Name
8682 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008683 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008684 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008685 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8686 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008687 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008688 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008689 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008690 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008691
8692 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008693 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008694 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008695
Richard Smith6b02d462012-12-08 08:32:28 +00008696 AddOverriddenMethods(ClassDecl, Destructor);
8697
8698 // We don't need to use SpecialMemberIsTrivial here; triviality for
8699 // destructors is easy to compute.
8700 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8701
8702 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008703 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008704
Douglas Gregor7454c562010-07-02 20:37:36 +00008705 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008706 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008707
Douglas Gregor7454c562010-07-02 20:37:36 +00008708 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008709 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008710 PushOnScopeChains(Destructor, S, false);
8711 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008712
Douglas Gregorf1203042010-07-01 19:09:28 +00008713 return Destructor;
8714}
8715
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008716void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008717 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008718 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008719 !Destructor->doesThisDeclarationHaveABody() &&
8720 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008721 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008722 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008723 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008724
Douglas Gregor54818f02010-05-12 16:39:35 +00008725 if (Destructor->isInvalidDecl())
8726 return;
8727
Eli Friedmaneaf34142012-10-18 20:14:08 +00008728 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008729
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008730 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008731 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8732 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008733
Douglas Gregor54818f02010-05-12 16:39:35 +00008734 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008735 Diag(CurrentLocation, diag::note_member_synthesized_at)
8736 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8737
8738 Destructor->setInvalidDecl();
8739 return;
8740 }
8741
Douglas Gregor73193272010-09-20 16:48:21 +00008742 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008743 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008744 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008745 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008746
8747 if (ASTMutationListener *L = getASTMutationListener()) {
8748 L->CompletedImplicitDefinition(Destructor);
8749 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008750}
8751
Richard Smith84973e52012-04-21 18:42:51 +00008752/// \brief Perform any semantic analysis which needs to be delayed until all
8753/// pending class member declarations have been parsed.
8754void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008755 // If the context is an invalid C++ class, just suppress these checks.
8756 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8757 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008758 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008759 DelayedDestructorExceptionSpecChecks.clear();
8760 return;
8761 }
8762 }
Richard Smith84973e52012-04-21 18:42:51 +00008763}
8764
Richard Smithd3b5c9082012-07-27 04:22:15 +00008765void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8766 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008767 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008768 "adjusting dtor exception specs was introduced in c++11");
8769
Sebastian Redl623ea822011-05-19 05:13:44 +00008770 // C++11 [class.dtor]p3:
8771 // A declaration of a destructor that does not have an exception-
8772 // specification is implicitly considered to have the same exception-
8773 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008774 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008775 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008776 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008777 return;
8778
Chandler Carruth9a797572011-09-20 04:55:26 +00008779 // Replace the destructor's type, building off the existing one. Fortunately,
8780 // the only thing of interest in the destructor type is its extended info.
8781 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008782 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8783 EPI.ExceptionSpecType = EST_Unevaluated;
8784 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008785 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008786
Sebastian Redl623ea822011-05-19 05:13:44 +00008787 // FIXME: If the destructor has a body that could throw, and the newly created
8788 // spec doesn't allow exceptions, we should emit a warning, because this
8789 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008790 // However, we don't have a body or an exception specification yet, so it
8791 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008792}
8793
Pavel Labath58934982013-08-30 08:52:28 +00008794namespace {
8795/// \brief An abstract base class for all helper classes used in building the
8796// copy/move operators. These classes serve as factory functions and help us
8797// avoid using the same Expr* in the AST twice.
8798class ExprBuilder {
8799 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8800 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8801
8802protected:
8803 static Expr *assertNotNull(Expr *E) {
8804 assert(E && "Expression construction must not fail.");
8805 return E;
8806 }
8807
8808public:
8809 ExprBuilder() {}
8810 virtual ~ExprBuilder() {}
8811
8812 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8813};
8814
8815class RefBuilder: public ExprBuilder {
8816 VarDecl *Var;
8817 QualType VarType;
8818
8819public:
8820 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8821 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8822 }
8823
8824 RefBuilder(VarDecl *Var, QualType VarType)
8825 : Var(Var), VarType(VarType) {}
8826};
8827
8828class ThisBuilder: public ExprBuilder {
8829public:
8830 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8831 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8832 }
8833};
8834
8835class CastBuilder: public ExprBuilder {
8836 const ExprBuilder &Builder;
8837 QualType Type;
8838 ExprValueKind Kind;
8839 const CXXCastPath &Path;
8840
8841public:
8842 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8843 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8844 CK_UncheckedDerivedToBase, Kind,
8845 &Path).take());
8846 }
8847
8848 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8849 const CXXCastPath &Path)
8850 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8851};
8852
8853class DerefBuilder: public ExprBuilder {
8854 const ExprBuilder &Builder;
8855
8856public:
8857 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8858 return assertNotNull(
8859 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8860 }
8861
8862 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8863};
8864
8865class MemberBuilder: public ExprBuilder {
8866 const ExprBuilder &Builder;
8867 QualType Type;
8868 CXXScopeSpec SS;
8869 bool IsArrow;
8870 LookupResult &MemberLookup;
8871
8872public:
8873 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8874 return assertNotNull(S.BuildMemberReferenceExpr(
8875 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8876 MemberLookup, 0).take());
8877 }
8878
8879 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8880 LookupResult &MemberLookup)
8881 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8882 MemberLookup(MemberLookup) {}
8883};
8884
8885class MoveCastBuilder: public ExprBuilder {
8886 const ExprBuilder &Builder;
8887
8888public:
8889 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8890 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8891 }
8892
8893 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8894};
8895
8896class LvalueConvBuilder: public ExprBuilder {
8897 const ExprBuilder &Builder;
8898
8899public:
8900 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8901 return assertNotNull(
8902 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8903 }
8904
8905 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8906};
8907
8908class SubscriptBuilder: public ExprBuilder {
8909 const ExprBuilder &Base;
8910 const ExprBuilder &Index;
8911
8912public:
8913 virtual Expr *build(Sema &S, SourceLocation Loc) const
8914 LLVM_OVERRIDE {
8915 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8916 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8917 }
8918
8919 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8920 : Base(Base), Index(Index) {}
8921};
8922
8923} // end anonymous namespace
8924
Richard Smith41ae3282012-11-14 00:50:40 +00008925/// When generating a defaulted copy or move assignment operator, if a field
8926/// should be copied with __builtin_memcpy rather than via explicit assignments,
8927/// do so. This optimization only applies for arrays of scalars, and for arrays
8928/// of class type where the selected copy/move-assignment operator is trivial.
8929static StmtResult
8930buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008931 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008932 // Compute the size of the memory buffer to be copied.
8933 QualType SizeType = S.Context.getSizeType();
8934 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8935 S.Context.getTypeSizeInChars(T).getQuantity());
8936
8937 // Take the address of the field references for "from" and "to". We
8938 // directly construct UnaryOperators here because semantic analysis
8939 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008940 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008941 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8942 S.Context.getPointerType(From->getType()),
8943 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008944 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008945 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8946 S.Context.getPointerType(To->getType()),
8947 VK_RValue, OK_Ordinary, Loc);
8948
8949 const Type *E = T->getBaseElementTypeUnsafe();
8950 bool NeedsCollectableMemCpy =
8951 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8952
8953 // Create a reference to the __builtin_objc_memmove_collectable function
8954 StringRef MemCpyName = NeedsCollectableMemCpy ?
8955 "__builtin_objc_memmove_collectable" :
8956 "__builtin_memcpy";
8957 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8958 Sema::LookupOrdinaryName);
8959 S.LookupName(R, S.TUScope, true);
8960
8961 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8962 if (!MemCpy)
8963 // Something went horribly wrong earlier, and we will have complained
8964 // about it.
8965 return StmtError();
8966
8967 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8968 VK_RValue, Loc, 0);
8969 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8970
8971 Expr *CallArgs[] = {
8972 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8973 };
8974 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8975 Loc, CallArgs, Loc);
8976
8977 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8978 return S.Owned(Call.takeAs<Stmt>());
8979}
8980
Sebastian Redl22653ba2011-08-30 19:58:05 +00008981/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008982/// \c To.
8983///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008984/// This routine is used to copy/move the members of a class with an
8985/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008986/// copied are arrays, this routine builds for loops to copy them.
8987///
8988/// \param S The Sema object used for type-checking.
8989///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008990/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008991///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008992/// \param T The type of the expressions being copied/moved. Both expressions
8993/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008994///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008995/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008996///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008997/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008998///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008999/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009000/// Otherwise, it's a non-static member subobject.
9001///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009002/// \param Copying Whether we're copying or moving.
9003///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009004/// \param Depth Internal parameter recording the depth of the recursion.
9005///
Richard Smith41ae3282012-11-14 00:50:40 +00009006/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9007/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009008static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009009buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009010 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009011 bool CopyingBaseSubobject, bool Copying,
9012 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009013 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009014 // Each subobject is assigned in the manner appropriate to its type:
9015 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009016 // - if the subobject is of class type, as if by a call to operator= with
9017 // the subobject as the object expression and the corresponding
9018 // subobject of x as a single function argument (as if by explicit
9019 // qualification; that is, ignoring any possible virtual overriding
9020 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009021 //
9022 // C++03 [class.copy]p13:
9023 // - if the subobject is of class type, the copy assignment operator for
9024 // the class is used (as if by explicit qualification; that is,
9025 // ignoring any possible virtual overriding functions in more derived
9026 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009027 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9028 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009029
Douglas Gregorb139cd52010-05-01 20:49:11 +00009030 // Look for operator=.
9031 DeclarationName Name
9032 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9033 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9034 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009035
Richard Smith52c0b582012-11-13 00:54:12 +00009036 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9037 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009038 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009039 LookupResult::Filter F = OpLookup.makeFilter();
9040 while (F.hasNext()) {
9041 NamedDecl *D = F.next();
9042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9043 if (Method->isCopyAssignmentOperator() ||
9044 (!Copying && Method->isMoveAssignmentOperator()))
9045 continue;
9046
9047 F.erase();
9048 }
9049 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009050 }
Richard Smith52c0b582012-11-13 00:54:12 +00009051
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009052 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009053 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009054 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009055 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009056 // ambiguities), we need to cast "this" to that subobject type; to
9057 // ensure that we don't go through the virtual call mechanism, we need
9058 // to qualify the operator= name with the base class (see below). However,
9059 // this means that if the base class has a protected copy assignment
9060 // operator, the protected member access check will fail. So, we
9061 // rewrite "protected" access to "public" access in this case, since we
9062 // know by construction that we're calling from a derived class.
9063 if (CopyingBaseSubobject) {
9064 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9065 L != LEnd; ++L) {
9066 if (L.getAccess() == AS_protected)
9067 L.setAccess(AS_public);
9068 }
9069 }
Richard Smith52c0b582012-11-13 00:54:12 +00009070
Douglas Gregorb139cd52010-05-01 20:49:11 +00009071 // Create the nested-name-specifier that will be used to qualify the
9072 // reference to operator=; this is required to suppress the virtual
9073 // call mechanism.
9074 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009075 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009076 SS.MakeTrivial(S.Context,
9077 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009078 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009079 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009080
Douglas Gregorb139cd52010-05-01 20:49:11 +00009081 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009082 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009083 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9084 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009085 /*FirstQualifierInScope=*/0,
9086 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009087 /*TemplateArgs=*/0,
9088 /*SuppressQualifierCheck=*/true);
9089 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009090 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009091
Douglas Gregorb139cd52010-05-01 20:49:11 +00009092 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009093
Pavel Labath58934982013-08-30 08:52:28 +00009094 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009095 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009096 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009097 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009098 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009099 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009100
Richard Smith41ae3282012-11-14 00:50:40 +00009101 // If we built a call to a trivial 'operator=' while copying an array,
9102 // bail out. We'll replace the whole shebang with a memcpy.
9103 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9104 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9105 return StmtResult((Stmt*)0);
9106
Richard Smith52c0b582012-11-13 00:54:12 +00009107 // Convert to an expression-statement, and clean up any produced
9108 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009109 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009110 }
John McCallab8c2732010-03-16 06:11:48 +00009111
Richard Smith52c0b582012-11-13 00:54:12 +00009112 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009113 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009114 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009115 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009116 ExprResult Assignment = S.CreateBuiltinBinOp(
9117 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009118 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009119 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009120 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009121 }
Richard Smith52c0b582012-11-13 00:54:12 +00009122
9123 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009124 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009125
Douglas Gregorb139cd52010-05-01 20:49:11 +00009126 // Construct a loop over the array bounds, e.g.,
9127 //
9128 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9129 //
9130 // that will copy each of the array elements.
9131 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009132
Douglas Gregorb139cd52010-05-01 20:49:11 +00009133 // Create the iteration variable.
9134 IdentifierInfo *IterationVarName = 0;
9135 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009136 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009137 llvm::raw_svector_ostream OS(Str);
9138 OS << "__i" << Depth;
9139 IterationVarName = &S.Context.Idents.get(OS.str());
9140 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009141 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009142 IterationVarName, SizeType,
9143 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009144 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009145
Douglas Gregorb139cd52010-05-01 20:49:11 +00009146 // Initialize the iteration variable to zero.
9147 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009148 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009149
Pavel Labath58934982013-08-30 08:52:28 +00009150 // Creates a reference to the iteration variable.
9151 RefBuilder IterationVarRef(IterationVar, SizeType);
9152 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009153
Douglas Gregorb139cd52010-05-01 20:49:11 +00009154 // Create the DeclStmt that holds the iteration variable.
9155 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009156
Douglas Gregorb139cd52010-05-01 20:49:11 +00009157 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009158 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9159 MoveCastBuilder FromIndexMove(FromIndexCopy);
9160 const ExprBuilder *FromIndex;
9161 if (Copying)
9162 FromIndex = &FromIndexCopy;
9163 else
9164 FromIndex = &FromIndexMove;
9165
9166 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009167
9168 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009169 StmtResult Copy =
9170 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009171 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009172 Copying, Depth + 1);
9173 // Bail out if copying fails or if we determined that we should use memcpy.
9174 if (Copy.isInvalid() || !Copy.get())
9175 return Copy;
9176
9177 // Create the comparison against the array bound.
9178 llvm::APInt Upper
9179 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9180 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009181 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009182 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9183 BO_NE, S.Context.BoolTy,
9184 VK_RValue, OK_Ordinary, Loc, false);
9185
9186 // Create the pre-increment of the iteration variable.
9187 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009188 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9189 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009190
Douglas Gregorb139cd52010-05-01 20:49:11 +00009191 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009192 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009193 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009194 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009195 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009196}
9197
Richard Smith41ae3282012-11-14 00:50:40 +00009198static StmtResult
9199buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009200 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009201 bool CopyingBaseSubobject, bool Copying) {
9202 // Maybe we should use a memcpy?
9203 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9204 T.isTriviallyCopyableType(S.Context))
9205 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9206
9207 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9208 CopyingBaseSubobject,
9209 Copying, 0));
9210
9211 // If we ended up picking a trivial assignment operator for an array of a
9212 // non-trivially-copyable class type, just emit a memcpy.
9213 if (!Result.isInvalid() && !Result.get())
9214 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9215
9216 return Result;
9217}
9218
Richard Smithd3b5c9082012-07-27 04:22:15 +00009219Sema::ImplicitExceptionSpecification
9220Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9221 CXXRecordDecl *ClassDecl = MD->getParent();
9222
9223 ImplicitExceptionSpecification ExceptSpec(*this);
9224 if (ClassDecl->isInvalidDecl())
9225 return ExceptSpec;
9226
9227 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9228 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9229 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9230
Douglas Gregor68e11362010-07-01 17:48:08 +00009231 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009232 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009233 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009234
9235 // It is unspecified whether or not an implicit copy assignment operator
9236 // attempts to deduplicate calls to assignment operators of virtual bases are
9237 // made. As such, this exception specification is effectively unspecified.
9238 // Based on a similar decision made for constness in C++0x, we're erring on
9239 // the side of assuming such calls to be made regardless of whether they
9240 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00009241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9242 BaseEnd = ClassDecl->bases_end();
9243 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009244 if (Base->isVirtual())
9245 continue;
9246
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009247 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00009248 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009249 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9250 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009251 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009252 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009253
9254 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9255 BaseEnd = ClassDecl->vbases_end();
9256 Base != BaseEnd; ++Base) {
9257 CXXRecordDecl *BaseClassDecl
9258 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9259 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9260 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009261 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009262 }
9263
Douglas Gregor68e11362010-07-01 17:48:08 +00009264 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9265 FieldEnd = ClassDecl->field_end();
9266 Field != FieldEnd;
9267 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009268 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009269 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9270 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009271 LookupCopyingAssignment(FieldClassDecl,
9272 ArgQuals | FieldType.getCVRQualifiers(),
9273 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009274 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009275 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009276 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009277
Richard Smithd3b5c9082012-07-27 04:22:15 +00009278 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009279}
9280
9281CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9282 // Note: The following rules are largely analoguous to the copy
9283 // constructor rules. Note that virtual bases are not taken into account
9284 // for determining the argument type of the operator. Note also that
9285 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009286 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009287
Richard Smith8bf22e52012-11-29 01:34:07 +00009288 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9289 if (DSM.isAlreadyBeingDeclared())
9290 return 0;
9291
Alexis Hunt119f3652011-05-14 05:23:20 +00009292 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9293 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009294 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9295 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009296 ArgType = ArgType.withConst();
9297 ArgType = Context.getLValueReferenceType(ArgType);
9298
Richard Smith99005e62013-05-07 03:19:20 +00009299 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9300 CXXCopyAssignment,
9301 Const);
9302
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009303 // An implicitly-declared copy assignment operator is an inline public
9304 // member of its class.
9305 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009306 SourceLocation ClassLoc = ClassDecl->getLocation();
9307 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009308 CXXMethodDecl *CopyAssignment =
9309 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9310 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9311 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009312 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009313 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009314 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009315
9316 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009317 FunctionProtoType::ExtProtoInfo EPI =
9318 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009319 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009320
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009321 // Add the parameter to the operator.
9322 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009323 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009324 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009325 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009326 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009327
Richard Smith6b02d462012-12-08 08:32:28 +00009328 AddOverriddenMethods(ClassDecl, CopyAssignment);
9329
9330 CopyAssignment->setTrivial(
9331 ClassDecl->needsOverloadResolutionForCopyAssignment()
9332 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9333 : ClassDecl->hasTrivialCopyAssignment());
9334
Richard Smith852265f2012-03-30 20:53:28 +00009335 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009336 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009337
Richard Smith6b02d462012-12-08 08:32:28 +00009338 // Note that we have added this copy-assignment operator.
9339 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9340
9341 if (Scope *S = getScopeForContext(ClassDecl))
9342 PushOnScopeChains(CopyAssignment, S, false);
9343 ClassDecl->addDecl(CopyAssignment);
9344
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009345 return CopyAssignment;
9346}
9347
Richard Smithd577fbb2013-06-13 03:23:42 +00009348/// Diagnose an implicit copy operation for a class which is odr-used, but
9349/// which is deprecated because the class has a user-declared copy constructor,
9350/// copy assignment operator, or destructor.
9351static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9352 SourceLocation UseLoc) {
9353 assert(CopyOp->isImplicit());
9354
9355 CXXRecordDecl *RD = CopyOp->getParent();
9356 CXXMethodDecl *UserDeclaredOperation = 0;
9357
9358 // In Microsoft mode, assignment operations don't affect constructors and
9359 // vice versa.
9360 if (RD->hasUserDeclaredDestructor()) {
9361 UserDeclaredOperation = RD->getDestructor();
9362 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9363 RD->hasUserDeclaredCopyConstructor() &&
9364 !S.getLangOpts().MicrosoftMode) {
9365 // Find any user-declared copy constructor.
9366 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9367 E = RD->ctor_end(); I != E; ++I) {
9368 if (I->isCopyConstructor()) {
9369 UserDeclaredOperation = *I;
9370 break;
9371 }
9372 }
9373 assert(UserDeclaredOperation);
9374 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9375 RD->hasUserDeclaredCopyAssignment() &&
9376 !S.getLangOpts().MicrosoftMode) {
9377 // Find any user-declared move assignment operator.
9378 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9379 E = RD->method_end(); I != E; ++I) {
9380 if (I->isCopyAssignmentOperator()) {
9381 UserDeclaredOperation = *I;
9382 break;
9383 }
9384 }
9385 assert(UserDeclaredOperation);
9386 }
9387
9388 if (UserDeclaredOperation) {
9389 S.Diag(UserDeclaredOperation->getLocation(),
9390 diag::warn_deprecated_copy_operation)
9391 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9392 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9393 S.Diag(UseLoc, diag::note_member_synthesized_at)
9394 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9395 : Sema::CXXCopyAssignment)
9396 << RD;
9397 }
9398}
9399
Douglas Gregorb139cd52010-05-01 20:49:11 +00009400void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9401 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009402 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403 CopyAssignOperator->isOverloadedOperator() &&
9404 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009405 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9406 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009407 "DefineImplicitCopyAssignment called for wrong function");
9408
9409 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9410
9411 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9412 CopyAssignOperator->setInvalidDecl();
9413 return;
9414 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009415
9416 // C++11 [class.copy]p18:
9417 // The [definition of an implicitly declared copy assignment operator] is
9418 // deprecated if the class has a user-declared copy constructor or a
9419 // user-declared destructor.
9420 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9421 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9422
Eli Friedman276dd182013-09-05 00:02:25 +00009423 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009424
Eli Friedmaneaf34142012-10-18 20:14:08 +00009425 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009426 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009427
9428 // C++0x [class.copy]p30:
9429 // The implicitly-defined or explicitly-defaulted copy assignment operator
9430 // for a non-union class X performs memberwise copy assignment of its
9431 // subobjects. The direct base classes of X are assigned first, in the
9432 // order of their declaration in the base-specifier-list, and then the
9433 // immediate non-static data members of X are assigned, in the order in
9434 // which they were declared in the class definition.
9435
9436 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009437 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438
9439 // The parameter for the "other" object, which we are copying from.
9440 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9441 Qualifiers OtherQuals = Other->getType().getQualifiers();
9442 QualType OtherRefType = Other->getType();
9443 if (const LValueReferenceType *OtherRef
9444 = OtherRefType->getAs<LValueReferenceType>()) {
9445 OtherRefType = OtherRef->getPointeeType();
9446 OtherQuals = OtherRefType.getQualifiers();
9447 }
9448
9449 // Our location for everything implicitly-generated.
9450 SourceLocation Loc = CopyAssignOperator->getLocation();
9451
Pavel Labath58934982013-08-30 08:52:28 +00009452 // Builds a DeclRefExpr for the "other" object.
9453 RefBuilder OtherRef(Other, OtherRefType);
9454
9455 // Builds the "this" pointer.
9456 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009457
9458 // Assign base classes.
9459 bool Invalid = false;
9460 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9461 E = ClassDecl->bases_end(); Base != E; ++Base) {
9462 // Form the assignment:
9463 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9464 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009465 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009466 Invalid = true;
9467 continue;
9468 }
9469
John McCallcf142162010-08-07 06:22:56 +00009470 CXXCastPath BasePath;
9471 BasePath.push_back(Base);
9472
Douglas Gregorb139cd52010-05-01 20:49:11 +00009473 // Construct the "from" expression, which is an implicit cast to the
9474 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009475 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9476 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009477
9478 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009479 DerefBuilder DerefThis(This);
9480 CastBuilder To(DerefThis,
9481 Context.getCVRQualifiedType(
9482 BaseType, CopyAssignOperator->getTypeQualifiers()),
9483 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009484
9485 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009486 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009487 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009488 /*CopyingBaseSubobject=*/true,
9489 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009490 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009491 Diag(CurrentLocation, diag::note_member_synthesized_at)
9492 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9493 CopyAssignOperator->setInvalidDecl();
9494 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009495 }
9496
9497 // Success! Record the copy.
9498 Statements.push_back(Copy.takeAs<Expr>());
9499 }
9500
Douglas Gregorb139cd52010-05-01 20:49:11 +00009501 // Assign non-static members.
9502 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9503 FieldEnd = ClassDecl->field_end();
9504 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009505 if (Field->isUnnamedBitfield())
9506 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009507
9508 if (Field->isInvalidDecl()) {
9509 Invalid = true;
9510 continue;
9511 }
9512
Douglas Gregorb139cd52010-05-01 20:49:11 +00009513 // Check for members of reference type; we can't copy those.
9514 if (Field->getType()->isReferenceType()) {
9515 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9516 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9517 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009518 Diag(CurrentLocation, diag::note_member_synthesized_at)
9519 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009520 Invalid = true;
9521 continue;
9522 }
9523
9524 // Check for members of const-qualified, non-class type.
9525 QualType BaseType = Context.getBaseElementType(Field->getType());
9526 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9527 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9528 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9529 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009530 Diag(CurrentLocation, diag::note_member_synthesized_at)
9531 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009532 Invalid = true;
9533 continue;
9534 }
John McCall1b1a1db2011-06-17 00:18:42 +00009535
9536 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009537 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9538 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009539
9540 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009541 if (FieldType->isIncompleteArrayType()) {
9542 assert(ClassDecl->hasFlexibleArrayMember() &&
9543 "Incomplete array type is not valid");
9544 continue;
9545 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009546
9547 // Build references to the field in the object we're copying from and to.
9548 CXXScopeSpec SS; // Intentionally empty
9549 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9550 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009551 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009552 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009553
9554 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9555
9556 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009557
Douglas Gregorb139cd52010-05-01 20:49:11 +00009558 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009559 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009560 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009561 /*CopyingBaseSubobject=*/false,
9562 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009563 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009564 Diag(CurrentLocation, diag::note_member_synthesized_at)
9565 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9566 CopyAssignOperator->setInvalidDecl();
9567 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009568 }
9569
9570 // Success! Record the copy.
9571 Statements.push_back(Copy.takeAs<Stmt>());
9572 }
9573
9574 if (!Invalid) {
9575 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009576 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009577
John McCalldadc5752010-08-24 06:29:42 +00009578 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009579 if (Return.isInvalid())
9580 Invalid = true;
9581 else {
9582 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009583
9584 if (Trap.hasErrorOccurred()) {
9585 Diag(CurrentLocation, diag::note_member_synthesized_at)
9586 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9587 Invalid = true;
9588 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009589 }
9590 }
9591
9592 if (Invalid) {
9593 CopyAssignOperator->setInvalidDecl();
9594 return;
9595 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009596
9597 StmtResult Body;
9598 {
9599 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009600 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009601 /*isStmtExpr=*/false);
9602 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9603 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009604 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009605
9606 if (ASTMutationListener *L = getASTMutationListener()) {
9607 L->CompletedImplicitDefinition(CopyAssignOperator);
9608 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009609}
9610
Sebastian Redl22653ba2011-08-30 19:58:05 +00009611Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009612Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9613 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009614
Richard Smithd3b5c9082012-07-27 04:22:15 +00009615 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009616 if (ClassDecl->isInvalidDecl())
9617 return ExceptSpec;
9618
9619 // C++0x [except.spec]p14:
9620 // An implicitly declared special member function (Clause 12) shall have an
9621 // exception-specification. [...]
9622
9623 // It is unspecified whether or not an implicit move assignment operator
9624 // attempts to deduplicate calls to assignment operators of virtual bases are
9625 // made. As such, this exception specification is effectively unspecified.
9626 // Based on a similar decision made for constness in C++0x, we're erring on
9627 // the side of assuming such calls to be made regardless of whether they
9628 // actually happen.
9629 // Note that a move constructor is not implicitly declared when there are
9630 // virtual bases, but it can still be user-declared and explicitly defaulted.
9631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9632 BaseEnd = ClassDecl->bases_end();
9633 Base != BaseEnd; ++Base) {
9634 if (Base->isVirtual())
9635 continue;
9636
9637 CXXRecordDecl *BaseClassDecl
9638 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9639 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009640 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009641 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009642 }
9643
9644 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9645 BaseEnd = ClassDecl->vbases_end();
9646 Base != BaseEnd; ++Base) {
9647 CXXRecordDecl *BaseClassDecl
9648 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9649 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009650 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009651 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652 }
9653
9654 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9655 FieldEnd = ClassDecl->field_end();
9656 Field != FieldEnd;
9657 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009658 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009659 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009660 if (CXXMethodDecl *MoveAssign =
9661 LookupMovingAssignment(FieldClassDecl,
9662 FieldType.getCVRQualifiers(),
9663 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009664 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009665 }
9666 }
9667
9668 return ExceptSpec;
9669}
9670
9671CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009672 assert(ClassDecl->needsImplicitMoveAssignment());
9673
Richard Smith8bf22e52012-11-29 01:34:07 +00009674 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9675 if (DSM.isAlreadyBeingDeclared())
9676 return 0;
9677
Sebastian Redl22653ba2011-08-30 19:58:05 +00009678 // Note: The following rules are largely analoguous to the move
9679 // constructor rules.
9680
Sebastian Redl22653ba2011-08-30 19:58:05 +00009681 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9682 QualType RetType = Context.getLValueReferenceType(ArgType);
9683 ArgType = Context.getRValueReferenceType(ArgType);
9684
Richard Smith99005e62013-05-07 03:19:20 +00009685 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9686 CXXMoveAssignment,
9687 false);
9688
Sebastian Redl22653ba2011-08-30 19:58:05 +00009689 // An implicitly-declared move assignment operator is an inline public
9690 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009691 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9692 SourceLocation ClassLoc = ClassDecl->getLocation();
9693 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009694 CXXMethodDecl *MoveAssignment =
9695 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9696 /*TInfo=*/0, /*StorageClass=*/SC_None,
9697 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009698 MoveAssignment->setAccess(AS_public);
9699 MoveAssignment->setDefaulted();
9700 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009701
Richard Smithd3b5c9082012-07-27 04:22:15 +00009702 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009703 FunctionProtoType::ExtProtoInfo EPI =
9704 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009705 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009706
Sebastian Redl22653ba2011-08-30 19:58:05 +00009707 // Add the parameter to the operator.
9708 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9709 ClassLoc, ClassLoc, /*Id=*/0,
9710 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009711 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009712 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009713
Richard Smith6b02d462012-12-08 08:32:28 +00009714 AddOverriddenMethods(ClassDecl, MoveAssignment);
9715
9716 MoveAssignment->setTrivial(
9717 ClassDecl->needsOverloadResolutionForMoveAssignment()
9718 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9719 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009720
Richard Smithd951a1d2012-02-18 02:02:13 +00009721 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009722 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9723 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009724 }
9725
Richard Smith6b02d462012-12-08 08:32:28 +00009726 // Note that we have added this copy-assignment operator.
9727 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9728
Sebastian Redl22653ba2011-08-30 19:58:05 +00009729 if (Scope *S = getScopeForContext(ClassDecl))
9730 PushOnScopeChains(MoveAssignment, S, false);
9731 ClassDecl->addDecl(MoveAssignment);
9732
Sebastian Redl22653ba2011-08-30 19:58:05 +00009733 return MoveAssignment;
9734}
9735
Richard Smithb2504bd2013-11-04 04:26:14 +00009736/// Check if we're implicitly defining a move assignment operator for a class
9737/// with virtual bases. Such a move assignment might move-assign the virtual
9738/// base multiple times.
9739static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9740 SourceLocation CurrentLocation) {
9741 assert(!Class->isDependentContext() && "should not define dependent move");
9742
9743 // Only a virtual base could get implicitly move-assigned multiple times.
9744 // Only a non-trivial move assignment can observe this. We only want to
9745 // diagnose if we implicitly define an assignment operator that assigns
9746 // two base classes, both of which move-assign the same virtual base.
9747 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9748 Class->getNumBases() < 2)
9749 return;
9750
9751 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9752 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9753 VBaseMap VBases;
9754
9755 for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9756 BE = Class->bases_end();
9757 BI != BE; ++BI) {
9758 Worklist.push_back(&*BI);
9759 while (!Worklist.empty()) {
9760 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9761 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9762
9763 // If the base has no non-trivial move assignment operators,
9764 // we don't care about moves from it.
9765 if (!Base->hasNonTrivialMoveAssignment())
9766 continue;
9767
9768 // If there's nothing virtual here, skip it.
9769 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9770 continue;
9771
9772 // If we're not actually going to call a move assignment for this base,
9773 // or the selected move assignment is trivial, skip it.
9774 Sema::SpecialMemberOverloadResult *SMOR =
9775 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9776 /*ConstArg*/false, /*VolatileArg*/false,
9777 /*RValueThis*/true, /*ConstThis*/false,
9778 /*VolatileThis*/false);
9779 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9780 !SMOR->getMethod()->isMoveAssignmentOperator())
9781 continue;
9782
9783 if (BaseSpec->isVirtual()) {
9784 // We're going to move-assign this virtual base, and its move
9785 // assignment operator is not trivial. If this can happen for
9786 // multiple distinct direct bases of Class, diagnose it. (If it
9787 // only happens in one base, we'll diagnose it when synthesizing
9788 // that base class's move assignment operator.)
9789 CXXBaseSpecifier *&Existing =
9790 VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9791 .first->second;
9792 if (Existing && Existing != BI) {
9793 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9794 << Class << Base;
9795 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9796 << (Base->getCanonicalDecl() ==
9797 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9798 << Base << Existing->getType() << Existing->getSourceRange();
9799 S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9800 << (Base->getCanonicalDecl() ==
9801 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9802 << Base << BI->getType() << BaseSpec->getSourceRange();
9803
9804 // Only diagnose each vbase once.
9805 Existing = 0;
9806 }
9807 } else {
9808 // Only walk over bases that have defaulted move assignment operators.
9809 // We assume that any user-provided move assignment operator handles
9810 // the multiple-moves-of-vbase case itself somehow.
9811 if (!SMOR->getMethod()->isDefaulted())
9812 continue;
9813
9814 // We're going to move the base classes of Base. Add them to the list.
9815 for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9816 BE = Base->bases_end();
9817 BI != BE; ++BI)
9818 Worklist.push_back(&*BI);
9819 }
9820 }
9821 }
9822}
9823
Sebastian Redl22653ba2011-08-30 19:58:05 +00009824void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9825 CXXMethodDecl *MoveAssignOperator) {
9826 assert((MoveAssignOperator->isDefaulted() &&
9827 MoveAssignOperator->isOverloadedOperator() &&
9828 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009829 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9830 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009831 "DefineImplicitMoveAssignment called for wrong function");
9832
9833 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9834
9835 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9836 MoveAssignOperator->setInvalidDecl();
9837 return;
9838 }
9839
Eli Friedman276dd182013-09-05 00:02:25 +00009840 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009841
Eli Friedmaneaf34142012-10-18 20:14:08 +00009842 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009843 DiagnosticErrorTrap Trap(Diags);
9844
9845 // C++0x [class.copy]p28:
9846 // The implicitly-defined or move assignment operator for a non-union class
9847 // X performs memberwise move assignment of its subobjects. The direct base
9848 // classes of X are assigned first, in the order of their declaration in the
9849 // base-specifier-list, and then the immediate non-static data members of X
9850 // are assigned, in the order in which they were declared in the class
9851 // definition.
9852
Richard Smithb2504bd2013-11-04 04:26:14 +00009853 // Issue a warning if our implicit move assignment operator will move
9854 // from a virtual base more than once.
9855 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009856
Sebastian Redl22653ba2011-08-30 19:58:05 +00009857 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009858 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009859
9860 // The parameter for the "other" object, which we are move from.
9861 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9862 QualType OtherRefType = Other->getType()->
9863 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009864 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009865 "Bad argument type of defaulted move assignment");
9866
9867 // Our location for everything implicitly-generated.
9868 SourceLocation Loc = MoveAssignOperator->getLocation();
9869
Pavel Labath58934982013-08-30 08:52:28 +00009870 // Builds a reference to the "other" object.
9871 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009873 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009874
Pavel Labath58934982013-08-30 08:52:28 +00009875 // Builds the "this" pointer.
9876 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009877
Sebastian Redl22653ba2011-08-30 19:58:05 +00009878 // Assign base classes.
9879 bool Invalid = false;
9880 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9881 E = ClassDecl->bases_end(); Base != E; ++Base) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009882 // C++11 [class.copy]p28:
9883 // It is unspecified whether subobjects representing virtual base classes
9884 // are assigned more than once by the implicitly-defined copy assignment
9885 // operator.
9886 // FIXME: Do not assign to a vbase that will be assigned by some other base
9887 // class. For a move-assignment, this can result in the vbase being moved
9888 // multiple times.
9889
Sebastian Redl22653ba2011-08-30 19:58:05 +00009890 // Form the assignment:
9891 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9892 QualType BaseType = Base->getType().getUnqualifiedType();
9893 if (!BaseType->isRecordType()) {
9894 Invalid = true;
9895 continue;
9896 }
9897
9898 CXXCastPath BasePath;
9899 BasePath.push_back(Base);
9900
9901 // Construct the "from" expression, which is an implicit cast to the
9902 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009903 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009904
9905 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009906 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009907
9908 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009909 CastBuilder To(DerefThis,
9910 Context.getCVRQualifiedType(
9911 BaseType, MoveAssignOperator->getTypeQualifiers()),
9912 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009913
9914 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009915 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009916 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009917 /*CopyingBaseSubobject=*/true,
9918 /*Copying=*/false);
9919 if (Move.isInvalid()) {
9920 Diag(CurrentLocation, diag::note_member_synthesized_at)
9921 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9922 MoveAssignOperator->setInvalidDecl();
9923 return;
9924 }
9925
9926 // Success! Record the move.
9927 Statements.push_back(Move.takeAs<Expr>());
9928 }
9929
Sebastian Redl22653ba2011-08-30 19:58:05 +00009930 // Assign non-static members.
9931 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9932 FieldEnd = ClassDecl->field_end();
9933 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009934 if (Field->isUnnamedBitfield())
9935 continue;
9936
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009937 if (Field->isInvalidDecl()) {
9938 Invalid = true;
9939 continue;
9940 }
9941
Sebastian Redl22653ba2011-08-30 19:58:05 +00009942 // Check for members of reference type; we can't move those.
9943 if (Field->getType()->isReferenceType()) {
9944 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9945 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9946 Diag(Field->getLocation(), diag::note_declared_at);
9947 Diag(CurrentLocation, diag::note_member_synthesized_at)
9948 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9949 Invalid = true;
9950 continue;
9951 }
9952
9953 // Check for members of const-qualified, non-class type.
9954 QualType BaseType = Context.getBaseElementType(Field->getType());
9955 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9956 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9957 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9958 Diag(Field->getLocation(), diag::note_declared_at);
9959 Diag(CurrentLocation, diag::note_member_synthesized_at)
9960 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9961 Invalid = true;
9962 continue;
9963 }
9964
9965 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009966 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9967 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009968
9969 QualType FieldType = Field->getType().getNonReferenceType();
9970 if (FieldType->isIncompleteArrayType()) {
9971 assert(ClassDecl->hasFlexibleArrayMember() &&
9972 "Incomplete array type is not valid");
9973 continue;
9974 }
9975
9976 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009977 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9978 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009979 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009980 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009981 MemberBuilder From(MoveOther, OtherRefType,
9982 /*IsArrow=*/false, MemberLookup);
9983 MemberBuilder To(This, getCurrentThisType(),
9984 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009985
Pavel Labath58934982013-08-30 08:52:28 +00009986 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009987 "Member reference with rvalue base must be rvalue except for reference "
9988 "members, which aren't allowed for move assignment.");
9989
Sebastian Redl22653ba2011-08-30 19:58:05 +00009990 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009991 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009992 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009993 /*CopyingBaseSubobject=*/false,
9994 /*Copying=*/false);
9995 if (Move.isInvalid()) {
9996 Diag(CurrentLocation, diag::note_member_synthesized_at)
9997 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9998 MoveAssignOperator->setInvalidDecl();
9999 return;
10000 }
Richard Smith11d19592012-11-12 23:33:00 +000010001
Sebastian Redl22653ba2011-08-30 19:58:05 +000010002 // Success! Record the copy.
10003 Statements.push_back(Move.takeAs<Stmt>());
10004 }
10005
10006 if (!Invalid) {
10007 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010008 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +000010009
10010 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
10011 if (Return.isInvalid())
10012 Invalid = true;
10013 else {
10014 Statements.push_back(Return.takeAs<Stmt>());
10015
10016 if (Trap.hasErrorOccurred()) {
10017 Diag(CurrentLocation, diag::note_member_synthesized_at)
10018 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10019 Invalid = true;
10020 }
10021 }
10022 }
10023
10024 if (Invalid) {
10025 MoveAssignOperator->setInvalidDecl();
10026 return;
10027 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010028
10029 StmtResult Body;
10030 {
10031 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010032 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010033 /*isStmtExpr=*/false);
10034 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10035 }
Sebastian Redl22653ba2011-08-30 19:58:05 +000010036 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10037
10038 if (ASTMutationListener *L = getASTMutationListener()) {
10039 L->CompletedImplicitDefinition(MoveAssignOperator);
10040 }
10041}
10042
Richard Smithd3b5c9082012-07-27 04:22:15 +000010043Sema::ImplicitExceptionSpecification
10044Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10045 CXXRecordDecl *ClassDecl = MD->getParent();
10046
10047 ImplicitExceptionSpecification ExceptSpec(*this);
10048 if (ClassDecl->isInvalidDecl())
10049 return ExceptSpec;
10050
10051 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10052 assert(T->getNumArgs() >= 1 && "not a copy ctor");
10053 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
10054
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010055 // C++ [except.spec]p14:
10056 // An implicitly declared special member function (Clause 12) shall have an
10057 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10059 BaseEnd = ClassDecl->bases_end();
10060 Base != BaseEnd;
10061 ++Base) {
10062 // Virtual bases are handled below.
10063 if (Base->isVirtual())
10064 continue;
10065
Douglas Gregora6d69502010-07-02 23:41:54 +000010066 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010067 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010068 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010069 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010070 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010071 }
10072 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10073 BaseEnd = ClassDecl->vbases_end();
10074 Base != BaseEnd;
10075 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010076 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010077 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010078 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010079 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010080 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010081 }
10082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10083 FieldEnd = ClassDecl->field_end();
10084 Field != FieldEnd;
10085 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010086 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010087 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10088 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010089 LookupCopyingConstructor(FieldClassDecl,
10090 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010091 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010092 }
10093 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010094
Richard Smithd3b5c9082012-07-27 04:22:15 +000010095 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010096}
10097
10098CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10099 CXXRecordDecl *ClassDecl) {
10100 // C++ [class.copy]p4:
10101 // If the class definition does not explicitly declare a copy
10102 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010103 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010104
Richard Smith8bf22e52012-11-29 01:34:07 +000010105 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10106 if (DSM.isAlreadyBeingDeclared())
10107 return 0;
10108
Alexis Hunt913820d2011-05-13 06:10:58 +000010109 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10110 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010111 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010112 if (Const)
10113 ArgType = ArgType.withConst();
10114 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010115
Richard Smithb5800092012-06-10 05:43:50 +000010116 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10117 CXXCopyConstructor,
10118 Const);
10119
Douglas Gregor54be3392010-07-01 17:57:27 +000010120 DeclarationName Name
10121 = Context.DeclarationNames.getCXXConstructorName(
10122 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010123 SourceLocation ClassLoc = ClassDecl->getLocation();
10124 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010125
10126 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010127 // member of its class.
10128 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010129 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010130 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010131 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010132 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010133 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010134
Richard Smithd3b5c9082012-07-27 04:22:15 +000010135 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010136 FunctionProtoType::ExtProtoInfo EPI =
10137 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010138 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010139 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010140
Douglas Gregor54be3392010-07-01 17:57:27 +000010141 // Add the parameter to the constructor.
10142 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010143 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010144 /*IdentifierInfo=*/0,
10145 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010146 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010147 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010148
Richard Smith6b02d462012-12-08 08:32:28 +000010149 CopyConstructor->setTrivial(
10150 ClassDecl->needsOverloadResolutionForCopyConstructor()
10151 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10152 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010153
Richard Smith852265f2012-03-30 20:53:28 +000010154 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010155 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010156
Richard Smith6b02d462012-12-08 08:32:28 +000010157 // Note that we have declared this constructor.
10158 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10159
10160 if (Scope *S = getScopeForContext(ClassDecl))
10161 PushOnScopeChains(CopyConstructor, S, false);
10162 ClassDecl->addDecl(CopyConstructor);
10163
Douglas Gregor54be3392010-07-01 17:57:27 +000010164 return CopyConstructor;
10165}
10166
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010167void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010168 CXXConstructorDecl *CopyConstructor) {
10169 assert((CopyConstructor->isDefaulted() &&
10170 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010171 !CopyConstructor->doesThisDeclarationHaveABody() &&
10172 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010173 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010174
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010175 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010176 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010177
Richard Smithd577fbb2013-06-13 03:23:42 +000010178 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010179 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010180 // deprecated if the class has a user-declared copy assignment operator
10181 // or a user-declared destructor.
10182 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10183 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10184
Eli Friedmaneaf34142012-10-18 20:14:08 +000010185 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010186 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010187
David Blaikie3fc2f912013-01-17 05:26:25 +000010188 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010189 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010190 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010191 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010192 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010193 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010194 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010195 CopyConstructor->setBody(ActOnCompoundStmt(
10196 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10197 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010198 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010199
Eli Friedman276dd182013-09-05 00:02:25 +000010200 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010201 if (ASTMutationListener *L = getASTMutationListener()) {
10202 L->CompletedImplicitDefinition(CopyConstructor);
10203 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010204}
10205
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010207Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10208 CXXRecordDecl *ClassDecl = MD->getParent();
10209
Sebastian Redl22653ba2011-08-30 19:58:05 +000010210 // C++ [except.spec]p14:
10211 // An implicitly declared special member function (Clause 12) shall have an
10212 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010213 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010214 if (ClassDecl->isInvalidDecl())
10215 return ExceptSpec;
10216
10217 // Direct base-class constructors.
10218 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10219 BEnd = ClassDecl->bases_end();
10220 B != BEnd; ++B) {
10221 if (B->isVirtual()) // Handled below.
10222 continue;
10223
10224 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10225 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010226 CXXConstructorDecl *Constructor =
10227 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 // If this is a deleted function, add it anyway. This might be conformant
10229 // with the standard. This might not. I'm not sure. It might not matter.
10230 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010231 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010232 }
10233 }
10234
10235 // Virtual base-class constructors.
10236 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10237 BEnd = ClassDecl->vbases_end();
10238 B != BEnd; ++B) {
10239 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010241 CXXConstructorDecl *Constructor =
10242 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010243 // If this is a deleted function, add it anyway. This might be conformant
10244 // with the standard. This might not. I'm not sure. It might not matter.
10245 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010246 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247 }
10248 }
10249
10250 // Field constructors.
10251 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10252 FEnd = ClassDecl->field_end();
10253 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010254 QualType FieldType = Context.getBaseElementType(F->getType());
10255 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10256 CXXConstructorDecl *Constructor =
10257 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010258 // If this is a deleted function, add it anyway. This might be conformant
10259 // with the standard. This might not. I'm not sure. It might not matter.
10260 // In particular, the problem is that this function never gets called. It
10261 // might just be ill-formed because this function attempts to refer to
10262 // a deleted function here.
10263 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010264 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010265 }
10266 }
10267
10268 return ExceptSpec;
10269}
10270
10271CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10272 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010273 assert(ClassDecl->needsImplicitMoveConstructor());
10274
Richard Smith8bf22e52012-11-29 01:34:07 +000010275 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10276 if (DSM.isAlreadyBeingDeclared())
10277 return 0;
10278
Sebastian Redl22653ba2011-08-30 19:58:05 +000010279 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10280 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010281
Richard Smithb5800092012-06-10 05:43:50 +000010282 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10283 CXXMoveConstructor,
10284 false);
10285
Sebastian Redl22653ba2011-08-30 19:58:05 +000010286 DeclarationName Name
10287 = Context.DeclarationNames.getCXXConstructorName(
10288 Context.getCanonicalType(ClassType));
10289 SourceLocation ClassLoc = ClassDecl->getLocation();
10290 DeclarationNameInfo NameInfo(Name, ClassLoc);
10291
Richard Smith99005e62013-05-07 03:19:20 +000010292 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010293 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010294 // member of its class.
10295 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010296 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010297 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010298 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 MoveConstructor->setAccess(AS_public);
10300 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010301
Richard Smithd3b5c9082012-07-27 04:22:15 +000010302 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010303 FunctionProtoType::ExtProtoInfo EPI =
10304 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010305 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010306 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010307
Sebastian Redl22653ba2011-08-30 19:58:05 +000010308 // Add the parameter to the constructor.
10309 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10310 ClassLoc, ClassLoc,
10311 /*IdentifierInfo=*/0,
10312 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010313 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010314 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010315
Richard Smith6b02d462012-12-08 08:32:28 +000010316 MoveConstructor->setTrivial(
10317 ClassDecl->needsOverloadResolutionForMoveConstructor()
10318 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10319 : ClassDecl->hasTrivialMoveConstructor());
10320
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010321 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010322 ClassDecl->setImplicitMoveConstructorIsDeleted();
10323 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010324 }
10325
10326 // Note that we have declared this constructor.
10327 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10328
10329 if (Scope *S = getScopeForContext(ClassDecl))
10330 PushOnScopeChains(MoveConstructor, S, false);
10331 ClassDecl->addDecl(MoveConstructor);
10332
10333 return MoveConstructor;
10334}
10335
10336void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10337 CXXConstructorDecl *MoveConstructor) {
10338 assert((MoveConstructor->isDefaulted() &&
10339 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010340 !MoveConstructor->doesThisDeclarationHaveABody() &&
10341 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010342 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10343
10344 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10345 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10346
Eli Friedmaneaf34142012-10-18 20:14:08 +000010347 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010348 DiagnosticErrorTrap Trap(Diags);
10349
David Blaikie3fc2f912013-01-17 05:26:25 +000010350 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010351 Trap.hasErrorOccurred()) {
10352 Diag(CurrentLocation, diag::note_member_synthesized_at)
10353 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10354 MoveConstructor->setInvalidDecl();
10355 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010356 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010357 MoveConstructor->setBody(ActOnCompoundStmt(
10358 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10359 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010360 }
10361
Eli Friedman276dd182013-09-05 00:02:25 +000010362 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010363
10364 if (ASTMutationListener *L = getASTMutationListener()) {
10365 L->CompletedImplicitDefinition(MoveConstructor);
10366 }
10367}
10368
Douglas Gregor74f7d502012-02-15 19:33:52 +000010369bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010370 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010371}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010372
10373void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010374 SourceLocation CurrentLocation,
10375 CXXConversionDecl *Conv) {
10376 CXXRecordDecl *Lambda = Conv->getParent();
10377 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10378 // If we are defining a specialization of a conversion to function-ptr
10379 // cache the deduced template arguments for this specialization
10380 // so that we can use them to retrieve the corresponding call-operator
10381 // and static-invoker.
10382 const TemplateArgumentList *DeducedTemplateArgs = 0;
10383
Douglas Gregor355efbb2012-02-17 03:02:34 +000010384
Faisal Vali571df122013-09-29 08:45:24 +000010385 // Retrieve the corresponding call-operator specialization.
10386 if (Lambda->isGenericLambda()) {
10387 assert(Conv->isFunctionTemplateSpecialization());
10388 FunctionTemplateDecl *CallOpTemplate =
10389 CallOp->getDescribedFunctionTemplate();
10390 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10391 void *InsertPos = 0;
10392 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10393 DeducedTemplateArgs->data(),
10394 DeducedTemplateArgs->size(),
10395 InsertPos);
10396 assert(CallOpSpec &&
10397 "Conversion operator must have a corresponding call operator");
10398 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10399 }
10400 // Mark the call operator referenced (and add to pending instantiations
10401 // if necessary).
10402 // For both the conversion and static-invoker template specializations
10403 // we construct their body's in this function, so no need to add them
10404 // to the PendingInstantiations.
10405 MarkFunctionReferenced(CurrentLocation, CallOp);
10406
Eli Friedmaneaf34142012-10-18 20:14:08 +000010407 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010408 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010409
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010410 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010411 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10412 // ... and get the corresponding specialization for a generic lambda.
10413 if (Lambda->isGenericLambda()) {
10414 assert(DeducedTemplateArgs &&
10415 "Must have deduced template arguments from Conversion Operator");
10416 FunctionTemplateDecl *InvokeTemplate =
10417 Invoker->getDescribedFunctionTemplate();
10418 void *InsertPos = 0;
10419 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10420 DeducedTemplateArgs->data(),
10421 DeducedTemplateArgs->size(),
10422 InsertPos);
10423 assert(InvokeSpec &&
10424 "Must have a corresponding static invoker specialization");
10425 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10426 }
10427 // Construct the body of the conversion function { return __invoke; }.
10428 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10429 VK_LValue, Conv->getLocation()).take();
10430 assert(FunctionRef && "Can't refer to __invoke function?");
10431 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10432 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10433 Conv->getLocation(),
10434 Conv->getLocation()));
10435
10436 Conv->markUsed(Context);
10437 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010438
Faisal Vali571df122013-09-29 08:45:24 +000010439 // Fill in the __invoke function with a dummy implementation. IR generation
10440 // will fill in the actual details.
10441 Invoker->markUsed(Context);
10442 Invoker->setReferenced();
10443 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10444
Douglas Gregord3b672c2012-02-16 01:06:16 +000010445 if (ASTMutationListener *L = getASTMutationListener()) {
10446 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010447 L->CompletedImplicitDefinition(Invoker);
10448 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010449}
10450
Faisal Vali571df122013-09-29 08:45:24 +000010451
10452
Douglas Gregord3b672c2012-02-16 01:06:16 +000010453void Sema::DefineImplicitLambdaToBlockPointerConversion(
10454 SourceLocation CurrentLocation,
10455 CXXConversionDecl *Conv)
10456{
Faisal Vali850da1a2013-09-29 17:08:32 +000010457 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010458
Eli Friedman276dd182013-09-05 00:02:25 +000010459 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010460
Eli Friedmaneaf34142012-10-18 20:14:08 +000010461 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010462 DiagnosticErrorTrap Trap(Diags);
10463
Douglas Gregored90df32012-02-22 05:02:47 +000010464 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010465 Expr *This = ActOnCXXThis(CurrentLocation).take();
10466 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010467
Eli Friedman98b01ed2012-03-01 04:01:32 +000010468 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10469 Conv->getLocation(),
10470 Conv, DerefThis);
10471
10472 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10473 // behavior. Note that only the general conversion function does this
10474 // (since it's unusable otherwise); in the case where we inline the
10475 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010476 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010477 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10478 CK_CopyAndAutoreleaseBlockObject,
10479 BuildBlock.get(), 0, VK_RValue);
10480
10481 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010482 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010483 Conv->setInvalidDecl();
10484 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010485 }
Douglas Gregored90df32012-02-22 05:02:47 +000010486
Douglas Gregored90df32012-02-22 05:02:47 +000010487 // Create the return statement that returns the block from the conversion
10488 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010489 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010490 if (Return.isInvalid()) {
10491 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10492 Conv->setInvalidDecl();
10493 return;
10494 }
10495
10496 // Set the body of the conversion function.
10497 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010498 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010499 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010500 Conv->getLocation()));
10501
Douglas Gregored90df32012-02-22 05:02:47 +000010502 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010503 if (ASTMutationListener *L = getASTMutationListener()) {
10504 L->CompletedImplicitDefinition(Conv);
10505 }
10506}
10507
Douglas Gregord2f70072012-03-10 06:53:13 +000010508/// \brief Determine whether the given list arguments contains exactly one
10509/// "real" (non-default) argument.
10510static bool hasOneRealArgument(MultiExprArg Args) {
10511 switch (Args.size()) {
10512 case 0:
10513 return false;
10514
10515 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010516 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010517 return false;
10518
10519 // fall through
10520 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010521 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010522 }
10523
10524 return false;
10525}
10526
John McCalldadc5752010-08-24 06:29:42 +000010527ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010528Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010529 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010530 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010531 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010532 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010533 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010534 unsigned ConstructKind,
10535 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010536 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010537
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010538 // C++0x [class.copy]p34:
10539 // When certain criteria are met, an implementation is allowed to
10540 // omit the copy/move construction of a class object, even if the
10541 // copy/move constructor and/or destructor for the object have
10542 // side effects. [...]
10543 // - when a temporary class object that has not been bound to a
10544 // reference (12.2) would be copied/moved to a class object
10545 // with the same cv-unqualified type, the copy/move operation
10546 // can be omitted by constructing the temporary object
10547 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010548 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010549 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010550 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010551 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010552 }
Mike Stump11289f42009-09-09 15:08:12 +000010553
10554 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010555 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010556 IsListInitialization, RequiresZeroInit,
10557 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010558}
10559
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010560/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10561/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010562ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010563Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10564 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010565 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010566 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010567 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010568 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010569 unsigned ConstructKind,
10570 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010571 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010572 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010573 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010574 HadMultipleCandidates,
10575 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010576 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10577 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010578}
10579
John McCall03c48482010-02-02 09:10:11 +000010580void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010581 if (VD->isInvalidDecl()) return;
10582
John McCall03c48482010-02-02 09:10:11 +000010583 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010584 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010585 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010586 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010587
Chandler Carruth86d17d32011-03-27 21:26:48 +000010588 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010589 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010590 CheckDestructorAccess(VD->getLocation(), Destructor,
10591 PDiag(diag::err_access_dtor_var)
10592 << VD->getDeclName()
10593 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010594 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010595
Chandler Carruth86d17d32011-03-27 21:26:48 +000010596 if (!VD->hasGlobalStorage()) return;
10597
10598 // Emit warning for non-trivial dtor in global scope (a real global,
10599 // class-static, function-static).
10600 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10601
10602 // TODO: this should be re-enabled for static locals by !CXAAtExit
10603 if (!VD->isStaticLocal())
10604 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010605}
10606
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010607/// \brief Given a constructor and the set of arguments provided for the
10608/// constructor, convert the arguments and add any required default arguments
10609/// to form a proper call to this constructor.
10610///
10611/// \returns true if an error occurred, false otherwise.
10612bool
10613Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10614 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010615 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010616 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010617 bool AllowExplicit,
10618 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010619 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10620 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010621 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010622
10623 const FunctionProtoType *Proto
10624 = Constructor->getType()->getAs<FunctionProtoType>();
10625 assert(Proto && "Constructor without a prototype?");
10626 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010627
10628 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010629 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010630 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010631 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010632 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010633
10634 VariadicCallType CallType =
10635 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010636 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010637 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010638 Proto, 0,
10639 llvm::makeArrayRef(Args, NumArgs),
10640 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010641 CallType, AllowExplicit,
10642 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010643 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010644
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010645 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010646
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010647 CheckConstructorCall(Constructor,
10648 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10649 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010650 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010651
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010652 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010653}
10654
Anders Carlssone363c8e2009-12-12 00:32:00 +000010655static inline bool
10656CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10657 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010658 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010659 if (isa<NamespaceDecl>(DC)) {
10660 return SemaRef.Diag(FnDecl->getLocation(),
10661 diag::err_operator_new_delete_declared_in_namespace)
10662 << FnDecl->getDeclName();
10663 }
10664
10665 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010666 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010667 return SemaRef.Diag(FnDecl->getLocation(),
10668 diag::err_operator_new_delete_declared_static)
10669 << FnDecl->getDeclName();
10670 }
10671
Anders Carlsson60659a82009-12-12 02:43:16 +000010672 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010673}
10674
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010675static inline bool
10676CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10677 CanQualType ExpectedResultType,
10678 CanQualType ExpectedFirstParamType,
10679 unsigned DependentParamTypeDiag,
10680 unsigned InvalidParamTypeDiag) {
10681 QualType ResultType =
10682 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10683
10684 // Check that the result type is not dependent.
10685 if (ResultType->isDependentType())
10686 return SemaRef.Diag(FnDecl->getLocation(),
10687 diag::err_operator_new_delete_dependent_result_type)
10688 << FnDecl->getDeclName() << ExpectedResultType;
10689
10690 // Check that the result type is what we expect.
10691 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10692 return SemaRef.Diag(FnDecl->getLocation(),
10693 diag::err_operator_new_delete_invalid_result_type)
10694 << FnDecl->getDeclName() << ExpectedResultType;
10695
10696 // A function template must have at least 2 parameters.
10697 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10698 return SemaRef.Diag(FnDecl->getLocation(),
10699 diag::err_operator_new_delete_template_too_few_parameters)
10700 << FnDecl->getDeclName();
10701
10702 // The function decl must have at least 1 parameter.
10703 if (FnDecl->getNumParams() == 0)
10704 return SemaRef.Diag(FnDecl->getLocation(),
10705 diag::err_operator_new_delete_too_few_parameters)
10706 << FnDecl->getDeclName();
10707
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010708 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010709 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10710 if (FirstParamType->isDependentType())
10711 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10712 << FnDecl->getDeclName() << ExpectedFirstParamType;
10713
10714 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010715 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010716 ExpectedFirstParamType)
10717 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10718 << FnDecl->getDeclName() << ExpectedFirstParamType;
10719
10720 return false;
10721}
10722
Anders Carlsson12308f42009-12-11 23:23:22 +000010723static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010724CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010725 // C++ [basic.stc.dynamic.allocation]p1:
10726 // A program is ill-formed if an allocation function is declared in a
10727 // namespace scope other than global scope or declared static in global
10728 // scope.
10729 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10730 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010731
10732 CanQualType SizeTy =
10733 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10734
10735 // C++ [basic.stc.dynamic.allocation]p1:
10736 // The return type shall be void*. The first parameter shall have type
10737 // std::size_t.
10738 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10739 SizeTy,
10740 diag::err_operator_new_dependent_param_type,
10741 diag::err_operator_new_param_type))
10742 return true;
10743
10744 // C++ [basic.stc.dynamic.allocation]p1:
10745 // The first parameter shall not have an associated default argument.
10746 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010747 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010748 diag::err_operator_new_default_arg)
10749 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10750
10751 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010752}
10753
10754static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010755CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010756 // C++ [basic.stc.dynamic.deallocation]p1:
10757 // A program is ill-formed if deallocation functions are declared in a
10758 // namespace scope other than global scope or declared static in global
10759 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010760 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10761 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010762
10763 // C++ [basic.stc.dynamic.deallocation]p2:
10764 // Each deallocation function shall return void and its first parameter
10765 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010766 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10767 SemaRef.Context.VoidPtrTy,
10768 diag::err_operator_delete_dependent_param_type,
10769 diag::err_operator_delete_param_type))
10770 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010771
Anders Carlsson12308f42009-12-11 23:23:22 +000010772 return false;
10773}
10774
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010775/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10776/// of this overloaded operator is well-formed. If so, returns false;
10777/// otherwise, emits appropriate diagnostics and returns true.
10778bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010779 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010780 "Expected an overloaded operator declaration");
10781
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010782 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10783
Mike Stump11289f42009-09-09 15:08:12 +000010784 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010785 // The allocation and deallocation functions, operator new,
10786 // operator new[], operator delete and operator delete[], are
10787 // described completely in 3.7.3. The attributes and restrictions
10788 // found in the rest of this subclause do not apply to them unless
10789 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010790 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010791 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010792
Anders Carlsson22f443f2009-12-12 00:26:23 +000010793 if (Op == OO_New || Op == OO_Array_New)
10794 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010795
10796 // C++ [over.oper]p6:
10797 // An operator function shall either be a non-static member
10798 // function or be a non-member function and have at least one
10799 // parameter whose type is a class, a reference to a class, an
10800 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010801 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10802 if (MethodDecl->isStatic())
10803 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010804 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010805 } else {
10806 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +000010807 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10808 ParamEnd = FnDecl->param_end();
10809 Param != ParamEnd; ++Param) {
10810 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010811 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10812 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010813 ClassOrEnumParam = true;
10814 break;
10815 }
10816 }
10817
Douglas Gregord69246b2008-11-17 16:14:12 +000010818 if (!ClassOrEnumParam)
10819 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010820 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010821 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010822 }
10823
10824 // C++ [over.oper]p8:
10825 // An operator function cannot have default arguments (8.3.6),
10826 // except where explicitly stated below.
10827 //
Mike Stump11289f42009-09-09 15:08:12 +000010828 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010829 // (C++ [over.call]p1).
10830 if (Op != OO_Call) {
10831 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10832 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010833 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +000010834 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010835 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010836 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010837 }
10838 }
10839
Douglas Gregor6cf08062008-11-10 13:38:07 +000010840 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10841 { false, false, false }
10842#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10843 , { Unary, Binary, MemberOnly }
10844#include "clang/Basic/OperatorKinds.def"
10845 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010846
Douglas Gregor6cf08062008-11-10 13:38:07 +000010847 bool CanBeUnaryOperator = OperatorUses[Op][0];
10848 bool CanBeBinaryOperator = OperatorUses[Op][1];
10849 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010850
10851 // C++ [over.oper]p8:
10852 // [...] Operator functions cannot have more or fewer parameters
10853 // than the number required for the corresponding operator, as
10854 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010855 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010856 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010857 if (Op != OO_Call &&
10858 ((NumParams == 1 && !CanBeUnaryOperator) ||
10859 (NumParams == 2 && !CanBeBinaryOperator) ||
10860 (NumParams < 1) || (NumParams > 2))) {
10861 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010862 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010863 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010864 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010865 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010866 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010867 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010868 assert(CanBeBinaryOperator &&
10869 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010870 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010871 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010872
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010873 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010874 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010875 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010876
Douglas Gregord69246b2008-11-17 16:14:12 +000010877 // Overloaded operators other than operator() cannot be variadic.
10878 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010879 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010880 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010881 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010882 }
10883
10884 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010885 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10886 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010887 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010888 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010889 }
10890
10891 // C++ [over.inc]p1:
10892 // The user-defined function called operator++ implements the
10893 // prefix and postfix ++ operator. If this function is a member
10894 // function with no parameters, or a non-member function with one
10895 // parameter of class or enumeration type, it defines the prefix
10896 // increment operator ++ for objects of that type. If the function
10897 // is a member function with one parameter (which shall be of type
10898 // int) or a non-member function with two parameters (the second
10899 // of which shall be of type int), it defines the postfix
10900 // increment operator ++ for objects of that type.
10901 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10902 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10903 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +000010904 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010905 ParamIsInt = BT->getKind() == BuiltinType::Int;
10906
Chris Lattner2b786902008-11-21 07:50:02 +000010907 if (!ParamIsInt)
10908 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010909 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010910 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010911 }
10912
Douglas Gregord69246b2008-11-17 16:14:12 +000010913 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010914}
Chris Lattner3b024a32008-12-17 07:09:26 +000010915
Alexis Huntc88db062010-01-13 09:01:02 +000010916/// CheckLiteralOperatorDeclaration - Check whether the declaration
10917/// of this literal operator function is well-formed. If so, returns
10918/// false; otherwise, emits appropriate diagnostics and returns true.
10919bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010920 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010921 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10922 << FnDecl->getDeclName();
10923 return true;
10924 }
10925
Richard Smith72eebee2012-03-04 09:41:16 +000010926 if (FnDecl->isExternC()) {
10927 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10928 return true;
10929 }
10930
Alexis Huntc88db062010-01-13 09:01:02 +000010931 bool Valid = false;
10932
Richard Smithbcc22fc2012-03-09 08:00:36 +000010933 // This might be the definition of a literal operator template.
10934 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10935 // This might be a specialization of a literal operator template.
10936 if (!TpDecl)
10937 TpDecl = FnDecl->getPrimaryTemplate();
10938
Richard Smithb8b41d32013-10-07 19:57:58 +000010939 // template <char...> type operator "" name() and
10940 // template <class T, T...> type operator "" name() are the only valid
10941 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010942 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010943 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010944 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010945 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10946 if (Params->size() == 1) {
10947 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010948 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010949
Alexis Hunt7dd26172010-04-07 23:11:06 +000010950 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010951 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10952 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10953 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010954 } else if (Params->size() == 2) {
10955 TemplateTypeParmDecl *PmType =
10956 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10957 NonTypeTemplateParmDecl *PmArgs =
10958 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10959
10960 // The second template parameter must be a parameter pack with the
10961 // first template parameter as its type.
10962 if (PmType && PmArgs &&
10963 !PmType->isTemplateParameterPack() &&
10964 PmArgs->isTemplateParameterPack()) {
10965 const TemplateTypeParmType *TArgs =
10966 PmArgs->getType()->getAs<TemplateTypeParmType>();
10967 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10968 TArgs->getIndex() == PmType->getIndex()) {
10969 Valid = true;
10970 if (ActiveTemplateInstantiations.empty())
10971 Diag(FnDecl->getLocation(),
10972 diag::ext_string_literal_operator_template);
10973 }
10974 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010975 }
10976 }
Richard Smith72eebee2012-03-04 09:41:16 +000010977 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010978 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010979 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10980
Richard Smith72eebee2012-03-04 09:41:16 +000010981 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010982
Alexis Hunt079a6f72010-04-07 22:57:35 +000010983 // unsigned long long int, long double, and any character type are allowed
10984 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010985 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10986 Context.hasSameType(T, Context.LongDoubleTy) ||
10987 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010988 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010989 Context.hasSameType(T, Context.Char16Ty) ||
10990 Context.hasSameType(T, Context.Char32Ty)) {
10991 if (++Param == FnDecl->param_end())
10992 Valid = true;
10993 goto FinishedParams;
10994 }
10995
Alexis Hunt079a6f72010-04-07 22:57:35 +000010996 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010997 const PointerType *PT = T->getAs<PointerType>();
10998 if (!PT)
10999 goto FinishedParams;
11000 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011001 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011002 goto FinishedParams;
11003 T = T.getUnqualifiedType();
11004
11005 // Move on to the second parameter;
11006 ++Param;
11007
11008 // If there is no second parameter, the first must be a const char *
11009 if (Param == FnDecl->param_end()) {
11010 if (Context.hasSameType(T, Context.CharTy))
11011 Valid = true;
11012 goto FinishedParams;
11013 }
11014
11015 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11016 // are allowed as the first parameter to a two-parameter function
11017 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011018 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011019 Context.hasSameType(T, Context.Char16Ty) ||
11020 Context.hasSameType(T, Context.Char32Ty)))
11021 goto FinishedParams;
11022
11023 // The second and final parameter must be an std::size_t
11024 T = (*Param)->getType().getUnqualifiedType();
11025 if (Context.hasSameType(T, Context.getSizeType()) &&
11026 ++Param == FnDecl->param_end())
11027 Valid = true;
11028 }
11029
11030 // FIXME: This diagnostic is absolutely terrible.
11031FinishedParams:
11032 if (!Valid) {
11033 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11034 << FnDecl->getDeclName();
11035 return true;
11036 }
11037
Richard Smith768cecc2012-03-09 08:16:22 +000011038 // A parameter-declaration-clause containing a default argument is not
11039 // equivalent to any of the permitted forms.
11040 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11041 ParamEnd = FnDecl->param_end();
11042 Param != ParamEnd; ++Param) {
11043 if ((*Param)->hasDefaultArg()) {
11044 Diag((*Param)->getDefaultArgRange().getBegin(),
11045 diag::err_literal_operator_default_argument)
11046 << (*Param)->getDefaultArgRange();
11047 break;
11048 }
11049 }
11050
Richard Smith0df56f42012-03-08 02:39:21 +000011051 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011052 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11053 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011054 // C++11 [usrlit.suffix]p1:
11055 // Literal suffix identifiers that do not start with an underscore
11056 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011057 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11058 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011059 }
Richard Smith0df56f42012-03-08 02:39:21 +000011060
Alexis Huntc88db062010-01-13 09:01:02 +000011061 return false;
11062}
11063
Douglas Gregor07665a62009-01-05 19:45:36 +000011064/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11065/// linkage specification, including the language and (if present)
11066/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11067/// the location of the language string literal, which is provided
11068/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11069/// the '{' brace. Otherwise, this linkage specification does not
11070/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011071Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11072 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011073 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +000011074 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +000011075 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011076 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011077 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011078 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011079 Language = LinkageSpecDecl::lang_cxx;
11080 else {
Douglas Gregor07665a62009-01-05 19:45:36 +000011081 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +000011082 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011083 }
Mike Stump11289f42009-09-09 15:08:12 +000011084
Chris Lattner438e5012008-12-17 07:13:27 +000011085 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011086
Douglas Gregor07665a62009-01-05 19:45:36 +000011087 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011088 ExternLoc, LangLoc, Language,
11089 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011090 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011091 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011092 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011093}
11094
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011095/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011096/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11097/// valid, it's the position of the closing '}' brace in a linkage
11098/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011099Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011100 Decl *LinkageSpec,
11101 SourceLocation RBraceLoc) {
11102 if (LinkageSpec) {
11103 if (RBraceLoc.isValid()) {
11104 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11105 LSDecl->setRBraceLoc(RBraceLoc);
11106 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011107 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011108 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011109 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011110}
11111
Michael Han84324352013-02-22 17:15:32 +000011112Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11113 AttributeList *AttrList,
11114 SourceLocation SemiLoc) {
11115 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11116 // Attribute declarations appertain to empty declaration so we handle
11117 // them here.
11118 if (AttrList)
11119 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011120
Michael Han84324352013-02-22 17:15:32 +000011121 CurContext->addDecl(ED);
11122 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011123}
11124
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011125/// \brief Perform semantic analysis for the variable declaration that
11126/// occurs within a C++ catch clause, returning the newly-created
11127/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011128VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011129 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011130 SourceLocation StartLoc,
11131 SourceLocation Loc,
11132 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011133 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011134 QualType ExDeclType = TInfo->getType();
11135
Sebastian Redl54c04d42008-12-22 19:15:10 +000011136 // Arrays and functions decay.
11137 if (ExDeclType->isArrayType())
11138 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11139 else if (ExDeclType->isFunctionType())
11140 ExDeclType = Context.getPointerType(ExDeclType);
11141
11142 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11143 // The exception-declaration shall not denote a pointer or reference to an
11144 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011145 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011146 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011147 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011148 Invalid = true;
11149 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011150
Sebastian Redl54c04d42008-12-22 19:15:10 +000011151 QualType BaseType = ExDeclType;
11152 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011153 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011154 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011155 BaseType = Ptr->getPointeeType();
11156 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011157 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011158 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011159 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011160 BaseType = Ref->getPointeeType();
11161 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011162 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011163 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011164 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011165 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011166 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011167
Mike Stump11289f42009-09-09 15:08:12 +000011168 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011169 RequireNonAbstractType(Loc, ExDeclType,
11170 diag::err_abstract_type_in_decl,
11171 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011172 Invalid = true;
11173
John McCall2ca705e2010-07-24 00:37:23 +000011174 // Only the non-fragile NeXT runtime currently supports C++ catches
11175 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011176 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011177 QualType T = ExDeclType;
11178 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11179 T = RT->getPointeeType();
11180
11181 if (T->isObjCObjectType()) {
11182 Diag(Loc, diag::err_objc_object_catch);
11183 Invalid = true;
11184 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011185 // FIXME: should this be a test for macosx-fragile specifically?
11186 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011187 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011188 }
11189 }
11190
Abramo Bagnaradff19302011-03-08 08:55:46 +000011191 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011192 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011193 ExDecl->setExceptionVariable(true);
11194
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011195 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011196 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011197 Invalid = true;
11198
Douglas Gregor750734c2011-07-06 18:14:43 +000011199 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011200 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011201 // Insulate this from anything else we might currently be parsing.
11202 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11203
Douglas Gregor6de584c2010-03-05 23:38:39 +000011204 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011205 // The object declared in an exception-declaration or, if the
11206 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011207 // copy-initialized (8.5) from the exception object. [...]
11208 // The object is destroyed when the handler exits, after the destruction
11209 // of any automatic objects initialized within the handler.
11210 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011211 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011212 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011213 QualType initType = ExDeclType;
11214
11215 InitializedEntity entity =
11216 InitializedEntity::InitializeVariable(ExDecl);
11217 InitializationKind initKind =
11218 InitializationKind::CreateCopy(Loc, SourceLocation());
11219
11220 Expr *opaqueValue =
11221 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011222 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11223 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011224 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011225 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011226 else {
11227 // If the constructor used was non-trivial, set this as the
11228 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011229 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011230 if (!construct->getConstructor()->isTrivial()) {
11231 Expr *init = MaybeCreateExprWithCleanups(construct);
11232 ExDecl->setInit(init);
11233 }
11234
11235 // And make sure it's destructable.
11236 FinalizeVarWithDestructor(ExDecl, recordType);
11237 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011238 }
11239 }
11240
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011241 if (Invalid)
11242 ExDecl->setInvalidDecl();
11243
11244 return ExDecl;
11245}
11246
11247/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11248/// handler.
John McCall48871652010-08-21 09:40:31 +000011249Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011250 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011251 bool Invalid = D.isInvalidType();
11252
11253 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011254 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11255 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011256 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11257 D.getIdentifierLoc());
11258 Invalid = true;
11259 }
11260
Sebastian Redl54c04d42008-12-22 19:15:10 +000011261 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011262 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011263 LookupOrdinaryName,
11264 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011265 // The scope should be freshly made just for us. There is just no way
11266 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011267 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011268 if (PrevDecl->isTemplateParameter()) {
11269 // Maybe we will complain about the shadowed template parameter.
11270 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011271 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011272 }
11273 }
11274
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011275 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011276 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11277 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011278 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011279 }
11280
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011281 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011282 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011283 D.getIdentifierLoc(),
11284 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011285 if (Invalid)
11286 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011287
Sebastian Redl54c04d42008-12-22 19:15:10 +000011288 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011289 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011290 PushOnScopeChains(ExDecl, S);
11291 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011292 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011293
Douglas Gregor758a8692009-06-17 21:51:59 +000011294 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011295 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011296}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011297
Abramo Bagnaraea947882011-03-08 16:41:52 +000011298Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011299 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011300 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011301 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011302 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011303
Richard Smithded9c2e2012-07-11 22:37:56 +000011304 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11305 return 0;
11306
11307 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11308 AssertMessage, RParenLoc, false);
11309}
11310
11311Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11312 Expr *AssertExpr,
11313 StringLiteral *AssertMessage,
11314 SourceLocation RParenLoc,
11315 bool Failed) {
11316 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11317 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011318 // In a static_assert-declaration, the constant-expression shall be a
11319 // constant expression that can be contextually converted to bool.
11320 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11321 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011322 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011323
Richard Smith902ca212011-12-14 23:32:26 +000011324 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011325 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011326 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011327 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011328 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011329
Richard Smithded9c2e2012-07-11 22:37:56 +000011330 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011331 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011332 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011333 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011334 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011335 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011336 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011337 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011338 }
Mike Stump11289f42009-09-09 15:08:12 +000011339
Abramo Bagnaraea947882011-03-08 16:41:52 +000011340 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011341 AssertExpr, AssertMessage, RParenLoc,
11342 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011343
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011344 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011345 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011346}
Sebastian Redlf769df52009-03-24 22:27:57 +000011347
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011348/// \brief Perform semantic analysis of the given friend type declaration.
11349///
11350/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011351FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011352 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011353 TypeSourceInfo *TSInfo) {
11354 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11355
11356 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011357 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011358
Richard Smithc8239732011-10-18 21:39:00 +000011359 // C++03 [class.friend]p2:
11360 // An elaborated-type-specifier shall be used in a friend declaration
11361 // for a class.*
11362 //
11363 // * The class-key of the elaborated-type-specifier is required.
11364 if (!ActiveTemplateInstantiations.empty()) {
11365 // Do not complain about the form of friend template types during
11366 // template instantiation; we will already have complained when the
11367 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011368 } else {
11369 if (!T->isElaboratedTypeSpecifier()) {
11370 // If we evaluated the type to a record type, suggest putting
11371 // a tag in front.
11372 if (const RecordType *RT = T->getAs<RecordType>()) {
11373 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011374
Nick Lewycky36722d22013-02-06 05:59:33 +000011375 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011376
Nick Lewycky36722d22013-02-06 05:59:33 +000011377 Diag(TypeRange.getBegin(),
11378 getLangOpts().CPlusPlus11 ?
11379 diag::warn_cxx98_compat_unelaborated_friend_type :
11380 diag::ext_unelaborated_friend_type)
11381 << (unsigned) RD->getTagKind()
11382 << T
11383 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11384 InsertionText);
11385 } else {
11386 Diag(FriendLoc,
11387 getLangOpts().CPlusPlus11 ?
11388 diag::warn_cxx98_compat_nonclass_type_friend :
11389 diag::ext_nonclass_type_friend)
11390 << T
11391 << TypeRange;
11392 }
11393 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011394 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011395 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011396 diag::warn_cxx98_compat_enum_friend :
11397 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011398 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011399 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011400 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011401
Nick Lewycky36722d22013-02-06 05:59:33 +000011402 // C++11 [class.friend]p3:
11403 // A friend declaration that does not declare a function shall have one
11404 // of the following forms:
11405 // friend elaborated-type-specifier ;
11406 // friend simple-type-specifier ;
11407 // friend typename-specifier ;
11408 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11409 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11410 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011411
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011412 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011413 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011414 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011415 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011416}
11417
John McCallace48cd2010-10-19 01:40:49 +000011418/// Handle a friend tag declaration where the scope specifier was
11419/// templated.
11420Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11421 unsigned TagSpec, SourceLocation TagLoc,
11422 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011423 IdentifierInfo *Name,
11424 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011425 AttributeList *Attr,
11426 MultiTemplateParamsArg TempParamLists) {
11427 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11428
11429 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011430 bool Invalid = false;
11431
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011432 if (TemplateParameterList *TemplateParams =
11433 MatchTemplateParametersToScopeSpecifier(
11434 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11435 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011436 if (TemplateParams->size() > 0) {
11437 // This is a declaration of a class template.
11438 if (Invalid)
11439 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011440
Eric Christopher6f228b52011-07-21 05:34:24 +000011441 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11442 SS, Name, NameLoc, Attr,
11443 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011444 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011445 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011446 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011447 } else {
11448 // The "template<>" header is extraneous.
11449 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11450 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11451 isExplicitSpecialization = true;
11452 }
11453 }
11454
11455 if (Invalid) return 0;
11456
John McCallace48cd2010-10-19 01:40:49 +000011457 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011458 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011459 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011460 isAllExplicitSpecializations = false;
11461 break;
11462 }
11463 }
11464
11465 // FIXME: don't ignore attributes.
11466
11467 // If it's explicit specializations all the way down, just forget
11468 // about the template header and build an appropriate non-templated
11469 // friend. TODO: for source fidelity, remember the headers.
11470 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011471 if (SS.isEmpty()) {
11472 bool Owned = false;
11473 bool IsDependent = false;
11474 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011475 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011476 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011477 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011478 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011479 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011480 /*UnderlyingType=*/TypeResult(),
11481 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011482 }
Richard Smith649c7b062014-01-08 00:56:48 +000011483
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011484 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011485 ElaboratedTypeKeyword Keyword
11486 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011487 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011488 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011489 if (T.isNull())
11490 return 0;
11491
11492 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11493 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011494 DependentNameTypeLoc TL =
11495 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011496 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011497 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011498 TL.setNameLoc(NameLoc);
11499 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011500 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011501 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011502 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011503 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011504 }
11505
11506 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011507 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011508 Friend->setAccess(AS_public);
11509 CurContext->addDecl(Friend);
11510 return Friend;
11511 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011512
11513 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11514
11515
John McCallace48cd2010-10-19 01:40:49 +000011516
11517 // Handle the case of a templated-scope friend class. e.g.
11518 // template <class T> class A<T>::B;
11519 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011520 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11521 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011522 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11523 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11524 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011525 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011526 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011527 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011528 TL.setNameLoc(NameLoc);
11529
11530 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011531 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011532 Friend->setAccess(AS_public);
11533 Friend->setUnsupportedFriend(true);
11534 CurContext->addDecl(Friend);
11535 return Friend;
11536}
11537
11538
John McCall11083da2009-09-16 22:47:08 +000011539/// Handle a friend type declaration. This works in tandem with
11540/// ActOnTag.
11541///
11542/// Notes on friend class templates:
11543///
11544/// We generally treat friend class declarations as if they were
11545/// declaring a class. So, for example, the elaborated type specifier
11546/// in a friend declaration is required to obey the restrictions of a
11547/// class-head (i.e. no typedefs in the scope chain), template
11548/// parameters are required to match up with simple template-ids, &c.
11549/// However, unlike when declaring a template specialization, it's
11550/// okay to refer to a template specialization without an empty
11551/// template parameter declaration, e.g.
11552/// friend class A<T>::B<unsigned>;
11553/// We permit this as a special case; if there are any template
11554/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011555/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011556Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011557 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011558 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011559
11560 assert(DS.isFriendSpecified());
11561 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11562
John McCall11083da2009-09-16 22:47:08 +000011563 // Try to convert the decl specifier to a type. This works for
11564 // friend templates because ActOnTag never produces a ClassTemplateDecl
11565 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011566 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011567 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11568 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011569 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011570 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011571
Douglas Gregor6c110f32010-12-16 01:14:37 +000011572 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11573 return 0;
11574
John McCall11083da2009-09-16 22:47:08 +000011575 // This is definitely an error in C++98. It's probably meant to
11576 // be forbidden in C++0x, too, but the specification is just
11577 // poorly written.
11578 //
11579 // The problem is with declarations like the following:
11580 // template <T> friend A<T>::foo;
11581 // where deciding whether a class C is a friend or not now hinges
11582 // on whether there exists an instantiation of A that causes
11583 // 'foo' to equal C. There are restrictions on class-heads
11584 // (which we declare (by fiat) elaborated friend declarations to
11585 // be) that makes this tractable.
11586 //
11587 // FIXME: handle "template <> friend class A<T>;", which
11588 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011589 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011590 Diag(Loc, diag::err_tagless_friend_type_template)
11591 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011592 return 0;
John McCall11083da2009-09-16 22:47:08 +000011593 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011594
John McCallaa74a0c2009-08-28 07:59:38 +000011595 // C++98 [class.friend]p1: A friend of a class is a function
11596 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011597 // This is fixed in DR77, which just barely didn't make the C++03
11598 // deadline. It's also a very silly restriction that seriously
11599 // affects inner classes and which nobody else seems to implement;
11600 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011601 //
11602 // But note that we could warn about it: it's always useless to
11603 // friend one of your own members (it's not, however, worthless to
11604 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011605
John McCall11083da2009-09-16 22:47:08 +000011606 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011607 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011608 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011609 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011610 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011611 TSI,
John McCall11083da2009-09-16 22:47:08 +000011612 DS.getFriendSpecLoc());
11613 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011614 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011615
11616 if (!D)
John McCall48871652010-08-21 09:40:31 +000011617 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011618
John McCall11083da2009-09-16 22:47:08 +000011619 D->setAccess(AS_public);
11620 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011621
John McCall48871652010-08-21 09:40:31 +000011622 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011623}
11624
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011625NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11626 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011627 const DeclSpec &DS = D.getDeclSpec();
11628
11629 assert(DS.isFriendSpecified());
11630 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11631
11632 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011633 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011634
11635 // C++ [class.friend]p1
11636 // A friend of a class is a function or class....
11637 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011638 // It *doesn't* see through dependent types, which is correct
11639 // according to [temp.arg.type]p3:
11640 // If a declaration acquires a function type through a
11641 // type dependent on a template-parameter and this causes
11642 // a declaration that does not use the syntactic form of a
11643 // function declarator to have a function type, the program
11644 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011645 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011646 Diag(Loc, diag::err_unexpected_friend);
11647
11648 // It might be worthwhile to try to recover by creating an
11649 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011650 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011651 }
11652
11653 // C++ [namespace.memdef]p3
11654 // - If a friend declaration in a non-local class first declares a
11655 // class or function, the friend class or function is a member
11656 // of the innermost enclosing namespace.
11657 // - The name of the friend is not found by simple name lookup
11658 // until a matching declaration is provided in that namespace
11659 // scope (either before or after the class declaration granting
11660 // friendship).
11661 // - If a friend function is called, its name may be found by the
11662 // name lookup that considers functions from namespaces and
11663 // classes associated with the types of the function arguments.
11664 // - When looking for a prior declaration of a class or a function
11665 // declared as a friend, scopes outside the innermost enclosing
11666 // namespace scope are not considered.
11667
John McCallde3fd222010-10-12 23:13:28 +000011668 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011669 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11670 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011671 assert(Name);
11672
Douglas Gregor6c110f32010-12-16 01:14:37 +000011673 // Check for unexpanded parameter packs.
11674 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11675 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11676 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11677 return 0;
11678
John McCall07e91c02009-08-06 02:15:43 +000011679 // The context we found the declaration in, or in which we should
11680 // create the declaration.
11681 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011682 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011683 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011684 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011685
Richard Smith114394f2013-08-09 04:35:01 +000011686 // There are five cases here.
11687 // - There's no scope specifier and we're in a local class. Only look
11688 // for functions declared in the immediately-enclosing block scope.
11689 // We recover from invalid scope qualifiers as if they just weren't there.
11690 FunctionDecl *FunctionContainingLocalClass = 0;
11691 if ((SS.isInvalid() || !SS.isSet()) &&
11692 (FunctionContainingLocalClass =
11693 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11694 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011695 // If a friend declaration appears in a local class and the name
11696 // specified is an unqualified name, a prior declaration is
11697 // looked up without considering scopes that are outside the
11698 // innermost enclosing non-class scope. For a friend function
11699 // declaration, if there is no prior declaration, the program is
11700 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011701
11702 // Find the innermost enclosing non-class scope. This is the block
11703 // scope containing the local class definition (or for a nested class,
11704 // the outer local class).
11705 DCScope = S->getFnParent();
11706
11707 // Look up the function name in the scope.
11708 Previous.clear(LookupLocalFriendName);
11709 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11710
11711 if (!Previous.empty()) {
11712 // All possible previous declarations must have the same context:
11713 // either they were declared at block scope or they are members of
11714 // one of the enclosing local classes.
11715 DC = Previous.getRepresentativeDecl()->getDeclContext();
11716 } else {
11717 // This is ill-formed, but provide the context that we would have
11718 // declared the function in, if we were permitted to, for error recovery.
11719 DC = FunctionContainingLocalClass;
11720 }
Richard Smith541b38b2013-09-20 01:15:31 +000011721 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011722
11723 // C++ [class.friend]p6:
11724 // A function can be defined in a friend declaration of a class if and
11725 // only if the class is a non-local class (9.8), the function name is
11726 // unqualified, and the function has namespace scope.
11727 if (D.isFunctionDefinition()) {
11728 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11729 }
11730
11731 // - There's no scope specifier, in which case we just go to the
11732 // appropriate scope and look for a function or function template
11733 // there as appropriate.
11734 } else if (SS.isInvalid() || !SS.isSet()) {
11735 // C++11 [namespace.memdef]p3:
11736 // If the name in a friend declaration is neither qualified nor
11737 // a template-id and the declaration is a function or an
11738 // elaborated-type-specifier, the lookup to determine whether
11739 // the entity has been previously declared shall not consider
11740 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011741 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011742
John McCallf7cfb222010-10-13 05:45:15 +000011743 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011744 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011745
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011746 // Skip class contexts. If someone can cite chapter and verse
11747 // for this behavior, that would be nice --- it's what GCC and
11748 // EDG do, and it seems like a reasonable intent, but the spec
11749 // really only says that checks for unqualified existing
11750 // declarations should stop at the nearest enclosing namespace,
11751 // not that they should only consider the nearest enclosing
11752 // namespace.
11753 while (DC->isRecord())
11754 DC = DC->getParent();
11755
11756 DeclContext *LookupDC = DC;
11757 while (LookupDC->isTransparentContext())
11758 LookupDC = LookupDC->getParent();
11759
11760 while (true) {
11761 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011762
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011763 if (!Previous.empty()) {
11764 DC = LookupDC;
11765 break;
John McCallf4776592010-10-14 22:22:28 +000011766 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011767
11768 if (isTemplateId) {
11769 if (isa<TranslationUnitDecl>(LookupDC)) break;
11770 } else {
11771 if (LookupDC->isFileContext()) break;
11772 }
11773 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011774 }
11775
John McCallccbc0322010-10-13 06:22:15 +000011776 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011777
John McCallde3fd222010-10-12 23:13:28 +000011778 // - There's a non-dependent scope specifier, in which case we
11779 // compute it and do a previous lookup there for a function
11780 // or function template.
11781 } else if (!SS.getScopeRep()->isDependent()) {
11782 DC = computeDeclContext(SS);
11783 if (!DC) return 0;
11784
11785 if (RequireCompleteDeclContext(SS, DC)) return 0;
11786
11787 LookupQualifiedName(Previous, DC);
11788
11789 // Ignore things found implicitly in the wrong scope.
11790 // TODO: better diagnostics for this case. Suggesting the right
11791 // qualified scope would be nice...
11792 LookupResult::Filter F = Previous.makeFilter();
11793 while (F.hasNext()) {
11794 NamedDecl *D = F.next();
11795 if (!DC->InEnclosingNamespaceSetOf(
11796 D->getDeclContext()->getRedeclContext()))
11797 F.erase();
11798 }
11799 F.done();
11800
11801 if (Previous.empty()) {
11802 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011803 Diag(Loc, diag::err_qualified_friend_not_found)
11804 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011805 return 0;
11806 }
11807
11808 // C++ [class.friend]p1: A friend of a class is a function or
11809 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011810 if (DC->Equals(CurContext))
11811 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011812 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011813 diag::warn_cxx98_compat_friend_is_member :
11814 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011815
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011816 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011817 // C++ [class.friend]p6:
11818 // A function can be defined in a friend declaration of a class if and
11819 // only if the class is a non-local class (9.8), the function name is
11820 // unqualified, and the function has namespace scope.
11821 SemaDiagnosticBuilder DB
11822 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11823
11824 DB << SS.getScopeRep();
11825 if (DC->isFileContext())
11826 DB << FixItHint::CreateRemoval(SS.getRange());
11827 SS.clear();
11828 }
John McCallde3fd222010-10-12 23:13:28 +000011829
11830 // - There's a scope specifier that does not match any template
11831 // parameter lists, in which case we use some arbitrary context,
11832 // create a method or method template, and wait for instantiation.
11833 // - There's a scope specifier that does match some template
11834 // parameter lists, which we don't handle right now.
11835 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011836 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011837 // C++ [class.friend]p6:
11838 // A function can be defined in a friend declaration of a class if and
11839 // only if the class is a non-local class (9.8), the function name is
11840 // unqualified, and the function has namespace scope.
11841 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11842 << SS.getScopeRep();
11843 }
11844
John McCallde3fd222010-10-12 23:13:28 +000011845 DC = CurContext;
11846 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011847 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011848
John McCallf7cfb222010-10-13 05:45:15 +000011849 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011850 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011851 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11852 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11853 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011854 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011855 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11856 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011857 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011858 }
John McCall07e91c02009-08-06 02:15:43 +000011859 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011860
Douglas Gregordd847ba2011-11-03 16:37:14 +000011861 // FIXME: This is an egregious hack to cope with cases where the scope stack
11862 // does not contain the declaration context, i.e., in an out-of-line
11863 // definition of a class.
11864 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11865 if (!DCScope) {
11866 FakeDCScope.setEntity(DC);
11867 DCScope = &FakeDCScope;
11868 }
Richard Smith114394f2013-08-09 04:35:01 +000011869
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011870 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011871 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011872 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011873 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011874
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011875 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011876
Richard Smith114394f2013-08-09 04:35:01 +000011877 // If we performed typo correction, we might have added a scope specifier
11878 // and changed the decl context.
11879 DC = ND->getDeclContext();
11880
John McCall759e32b2009-08-31 22:39:49 +000011881 // Add the function declaration to the appropriate lookup tables,
11882 // adjusting the redeclarations list as necessary. We don't
11883 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011884 //
John McCall759e32b2009-08-31 22:39:49 +000011885 // Also update the scope-based lookup if the target context's
11886 // lookup context is in lexical scope.
11887 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011888 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011889 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011890 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011891 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011892 }
John McCallaa74a0c2009-08-28 07:59:38 +000011893
11894 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011895 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011896 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011897 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011898 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011899
John McCalla0a96892012-08-10 03:15:35 +000011900 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011901 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011902 } else {
11903 if (DC->isRecord()) CheckFriendAccess(ND);
11904
John McCall2c2eb122010-10-16 06:59:13 +000011905 FunctionDecl *FD;
11906 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11907 FD = FTD->getTemplatedDecl();
11908 else
11909 FD = cast<FunctionDecl>(ND);
11910
David Majnemer502b0ed2013-06-25 23:09:30 +000011911 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11912 // default argument expression, that declaration shall be a definition
11913 // and shall be the only declaration of the function or function
11914 // template in the translation unit.
11915 if (functionDeclHasDefaultArgument(FD)) {
11916 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11917 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11918 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11919 } else if (!D.isFunctionDefinition())
11920 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11921 }
11922
John McCall2c2eb122010-10-16 06:59:13 +000011923 // Mark templated-scope function declarations as unsupported.
11924 if (FD->getNumTemplateParameterLists())
11925 FrD->setUnsupportedFriend(true);
11926 }
John McCallde3fd222010-10-12 23:13:28 +000011927
John McCall48871652010-08-21 09:40:31 +000011928 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011929}
11930
John McCall48871652010-08-21 09:40:31 +000011931void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11932 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011933
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011934 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011935 if (!Fn) {
11936 Diag(DelLoc, diag::err_deleted_non_function);
11937 return;
11938 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011939
Douglas Gregorec9fd132012-01-14 16:38:05 +000011940 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011941 // Don't consider the implicit declaration we generate for explicit
11942 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikieaf031a92012-06-29 18:00:25 +000011943 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11944 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011945 Diag(DelLoc, diag::err_deleted_decl_not_first);
11946 Diag(Prev->getLocation(), diag::note_previous_declaration);
11947 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011948 // If the declaration wasn't the first, we delete the function anyway for
11949 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011950 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011951 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011952
11953 if (Fn->isDeleted())
11954 return;
11955
11956 // See if we're deleting a function which is already known to override a
11957 // non-deleted virtual function.
11958 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11959 bool IssuedDiagnostic = false;
11960 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11961 E = MD->end_overridden_methods();
11962 I != E; ++I) {
11963 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11964 if (!IssuedDiagnostic) {
11965 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11966 IssuedDiagnostic = true;
11967 }
11968 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11969 }
11970 }
11971 }
11972
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011973 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011974}
Sebastian Redl4c018662009-04-27 21:33:24 +000011975
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011976void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011977 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011978
11979 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011980 if (MD->getParent()->isDependentType()) {
11981 MD->setDefaulted();
11982 MD->setExplicitlyDefaulted();
11983 return;
11984 }
11985
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011986 CXXSpecialMember Member = getSpecialMember(MD);
11987 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011988 if (!MD->isInvalidDecl())
11989 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011990 return;
11991 }
11992
11993 MD->setDefaulted();
11994 MD->setExplicitlyDefaulted();
11995
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011996 // If this definition appears within the record, do the checking when
11997 // the record is complete.
11998 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011999 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012000 // Find the uninstantiated declaration that actually had the '= default'
12001 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012002 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012003
Richard Smith3901dfe2013-03-27 00:22:47 +000012004 // If the method was defaulted on its first declaration, we will have
12005 // already performed the checking in CheckCompletedCXXClass. Such a
12006 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012007 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012008 return;
12009
Richard Smithd3b5c9082012-07-27 04:22:15 +000012010 CheckExplicitlyDefaultedSpecialMember(MD);
12011
Richard Smithbd305122012-12-11 01:14:52 +000012012 // The exception specification is needed because we are defining the
12013 // function.
12014 ResolveExceptionSpec(DefaultLoc,
12015 MD->getType()->castAs<FunctionProtoType>());
12016
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012017 if (MD->isInvalidDecl())
12018 return;
12019
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012020 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012021 case CXXDefaultConstructor:
12022 DefineImplicitDefaultConstructor(DefaultLoc,
12023 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012024 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012025 case CXXCopyConstructor:
12026 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012027 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012028 case CXXCopyAssignment:
12029 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012030 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012031 case CXXDestructor:
12032 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012033 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012034 case CXXMoveConstructor:
12035 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012036 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012037 case CXXMoveAssignment:
12038 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012039 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012040 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012041 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012042 }
12043 } else {
12044 Diag(DefaultLoc, diag::err_default_special_members);
12045 }
12046}
12047
Sebastian Redl4c018662009-04-27 21:33:24 +000012048static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012049 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012050 Stmt *SubStmt = *CI;
12051 if (!SubStmt)
12052 continue;
12053 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012054 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012055 diag::err_return_in_constructor_handler);
12056 if (!isa<Expr>(SubStmt))
12057 SearchForReturnInStmt(Self, SubStmt);
12058 }
12059}
12060
12061void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12062 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12063 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12064 SearchForReturnInStmt(*this, Handler);
12065 }
12066}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012067
David Blaikie68f71a32013-01-18 23:03:15 +000012068bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012069 const CXXMethodDecl *Old) {
12070 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12071 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12072
12073 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12074
12075 // If the calling conventions match, everything is fine
12076 if (NewCC == OldCC)
12077 return false;
12078
Hans Wennborg2545efe2013-12-11 17:42:11 +000012079 // If the calling conventions mismatch because the new function is static,
12080 // suppress the calling convention mismatch error; the error about static
12081 // function override (err_static_overrides_virtual from
12082 // Sema::CheckFunctionDeclaration) is more clear.
12083 if (New->getStorageClass() == SC_Static)
12084 return false;
12085
Reid Kleckner78af0702013-08-27 23:08:25 +000012086 Diag(New->getLocation(),
12087 diag::err_conflicting_overriding_cc_attributes)
12088 << New->getDeclName() << New->getType() << Old->getType();
12089 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12090 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012091}
12092
Mike Stump11289f42009-09-09 15:08:12 +000012093bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012094 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000012095 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12096 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012097
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012098 if (Context.hasSameType(NewTy, OldTy) ||
12099 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012100 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012101
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012102 // Check if the return types are covariant
12103 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012104
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012105 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012106 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12107 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012108 NewClassTy = NewPT->getPointeeType();
12109 OldClassTy = OldPT->getPointeeType();
12110 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012111 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12112 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12113 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12114 NewClassTy = NewRT->getPointeeType();
12115 OldClassTy = OldRT->getPointeeType();
12116 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012117 }
12118 }
Mike Stump11289f42009-09-09 15:08:12 +000012119
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012120 // The return types aren't either both pointers or references to a class type.
12121 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012122 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012123 diag::err_different_return_type_for_overriding_virtual_function)
12124 << New->getDeclName() << NewTy << OldTy;
12125 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012126
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012127 return true;
12128 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012129
Anders Carlssone60365b2009-12-31 18:34:24 +000012130 // C++ [class.virtual]p6:
12131 // If the return type of D::f differs from the return type of B::f, the
12132 // class type in the return type of D::f shall be complete at the point of
12133 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012134 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12135 if (!RT->isBeingDefined() &&
12136 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012137 diag::err_covariant_return_incomplete,
12138 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012139 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012140 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012141
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012142 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012143 // Check if the new class derives from the old class.
12144 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12145 Diag(New->getLocation(),
12146 diag::err_covariant_return_not_derived)
12147 << New->getDeclName() << NewTy << OldTy;
12148 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12149 return true;
12150 }
Mike Stump11289f42009-09-09 15:08:12 +000012151
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012152 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012153 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012154 diag::err_covariant_return_inaccessible_base,
12155 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12156 // FIXME: Should this point to the return type?
12157 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012158 // FIXME: this note won't trigger for delayed access control
12159 // diagnostics, and it's impossible to get an undelayed error
12160 // here from access control during the original parse because
12161 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012162 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12163 return true;
12164 }
12165 }
Mike Stump11289f42009-09-09 15:08:12 +000012166
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012167 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012168 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012169 Diag(New->getLocation(),
12170 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012171 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012172 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12173 return true;
12174 };
Mike Stump11289f42009-09-09 15:08:12 +000012175
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012176
12177 // The new class type must have the same or less qualifiers as the old type.
12178 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12179 Diag(New->getLocation(),
12180 diag::err_covariant_return_type_class_type_more_qualified)
12181 << New->getDeclName() << NewTy << OldTy;
12182 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12183 return true;
12184 };
Mike Stump11289f42009-09-09 15:08:12 +000012185
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012186 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012187}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012188
Douglas Gregor21920e372009-12-01 17:24:26 +000012189/// \brief Mark the given method pure.
12190///
12191/// \param Method the method to be marked pure.
12192///
12193/// \param InitRange the source range that covers the "0" initializer.
12194bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012195 SourceLocation EndLoc = InitRange.getEnd();
12196 if (EndLoc.isValid())
12197 Method->setRangeEnd(EndLoc);
12198
Douglas Gregor21920e372009-12-01 17:24:26 +000012199 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12200 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012201 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012202 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012203
12204 if (!Method->isInvalidDecl())
12205 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12206 << Method->getDeclName() << InitRange;
12207 return true;
12208}
12209
Douglas Gregor926410d2012-02-21 02:22:07 +000012210/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012211static bool isStaticDataMember(const Decl *D) {
12212 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12213 return Var->isStaticDataMember();
12214
12215 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012216}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012217
John McCall1f4ee7b2009-12-19 09:28:58 +000012218/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12219/// an initializer for the out-of-line declaration 'Dcl'. The scope
12220/// is a fresh scope pushed for just this purpose.
12221///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012222/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12223/// static data member of class X, names should be looked up in the scope of
12224/// class X.
John McCall48871652010-08-21 09:40:31 +000012225void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012226 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012227 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012228
Richard Smitha2302242013-12-05 07:51:02 +000012229 // We will always have a nested name specifier here, but this declaration
12230 // might not be out of line if the specifier names the current namespace:
12231 // extern int n;
12232 // int ::n = 0;
12233 if (D->isOutOfLine())
12234 EnterDeclaratorContext(S, D->getDeclContext());
12235
Douglas Gregor926410d2012-02-21 02:22:07 +000012236 // If we are parsing the initializer for a static data member, push a
12237 // new expression evaluation context that is associated with this static
12238 // data member.
12239 if (isStaticDataMember(D))
12240 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012241}
12242
12243/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012244/// initializer for the out-of-line declaration 'D'.
12245void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012246 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012247 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012248
Douglas Gregor926410d2012-02-21 02:22:07 +000012249 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012250 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012251
Richard Smitha2302242013-12-05 07:51:02 +000012252 if (D->isOutOfLine())
12253 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012254}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012255
12256/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12257/// C++ if/switch/while/for statement.
12258/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012259DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012260 // C++ 6.4p2:
12261 // The declarator shall not specify a function or an array.
12262 // The type-specifier-seq shall not contain typedef and shall not declare a
12263 // new class or enumeration.
12264 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12265 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012266
12267 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012268 if (!Dcl)
12269 return true;
12270
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012271 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12272 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012273 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012274 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012275 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012276
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012277 return Dcl;
12278}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012279
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012280void Sema::LoadExternalVTableUses() {
12281 if (!ExternalSource)
12282 return;
12283
12284 SmallVector<ExternalVTableUse, 4> VTables;
12285 ExternalSource->ReadUsedVTables(VTables);
12286 SmallVector<VTableUse, 4> NewUses;
12287 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12288 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12289 = VTablesUsed.find(VTables[I].Record);
12290 // Even if a definition wasn't required before, it may be required now.
12291 if (Pos != VTablesUsed.end()) {
12292 if (!Pos->second && VTables[I].DefinitionRequired)
12293 Pos->second = true;
12294 continue;
12295 }
12296
12297 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12298 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12299 }
12300
12301 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12302}
12303
Douglas Gregor88d292c2010-05-13 16:44:06 +000012304void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12305 bool DefinitionRequired) {
12306 // Ignore any vtable uses in unevaluated operands or for classes that do
12307 // not have a vtable.
12308 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012309 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012310 return;
12311
Douglas Gregor88d292c2010-05-13 16:44:06 +000012312 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012313 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012314 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12315 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12316 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12317 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012318 // If we already had an entry, check to see if we are promoting this vtable
12319 // to required a definition. If so, we need to reappend to the VTableUses
12320 // list, since we may have already processed the first entry.
12321 if (DefinitionRequired && !Pos.first->second) {
12322 Pos.first->second = true;
12323 } else {
12324 // Otherwise, we can early exit.
12325 return;
12326 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012327 }
12328
12329 // Local classes need to have their virtual members marked
12330 // immediately. For all other classes, we mark their virtual members
12331 // at the end of the translation unit.
12332 if (Class->isLocalClass())
12333 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012334 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012335 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012336}
12337
Douglas Gregor88d292c2010-05-13 16:44:06 +000012338bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012339 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012340 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012341 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012342
Douglas Gregor88d292c2010-05-13 16:44:06 +000012343 // Note: The VTableUses vector could grow as a result of marking
12344 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012345 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012346 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012347 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012348 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012349 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012350 if (!Class)
12351 continue;
12352
12353 SourceLocation Loc = VTableUses[I].second;
12354
Richard Smithd3b5c9082012-07-27 04:22:15 +000012355 bool DefineVTable = true;
12356
Douglas Gregor88d292c2010-05-13 16:44:06 +000012357 // If this class has a key function, but that key function is
12358 // defined in another translation unit, we don't need to emit the
12359 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012360 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012361 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012362 // The key function is in another translation unit.
12363 DefineVTable = false;
12364 TemplateSpecializationKind TSK =
12365 KeyFunction->getTemplateSpecializationKind();
12366 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12367 TSK != TSK_ImplicitInstantiation &&
12368 "Instantiations don't have key functions");
12369 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012370 } else if (!KeyFunction) {
12371 // If we have a class with no key function that is the subject
12372 // of an explicit instantiation declaration, suppress the
12373 // vtable; it will live with the explicit instantiation
12374 // definition.
12375 bool IsExplicitInstantiationDeclaration
12376 = Class->getTemplateSpecializationKind()
12377 == TSK_ExplicitInstantiationDeclaration;
12378 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12379 REnd = Class->redecls_end();
12380 R != REnd; ++R) {
12381 TemplateSpecializationKind TSK
12382 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12383 if (TSK == TSK_ExplicitInstantiationDeclaration)
12384 IsExplicitInstantiationDeclaration = true;
12385 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12386 IsExplicitInstantiationDeclaration = false;
12387 break;
12388 }
12389 }
12390
12391 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012392 DefineVTable = false;
12393 }
12394
12395 // The exception specifications for all virtual members may be needed even
12396 // if we are not providing an authoritative form of the vtable in this TU.
12397 // We may choose to emit it available_externally anyway.
12398 if (!DefineVTable) {
12399 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12400 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012401 }
12402
12403 // Mark all of the virtual members of this class as referenced, so
12404 // that we can build a vtable. Then, tell the AST consumer that a
12405 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012406 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012407 MarkVirtualMembersReferenced(Loc, Class);
12408 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12409 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12410
12411 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012412 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012413 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012414 const FunctionDecl *KeyFunctionDef = 0;
12415 if (!KeyFunction ||
12416 (KeyFunction->hasBody(KeyFunctionDef) &&
12417 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012418 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12419 TSK_ExplicitInstantiationDefinition
12420 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12421 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012422 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012423 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012424 VTableUses.clear();
12425
Douglas Gregor97509692011-04-22 22:25:37 +000012426 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012427}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012428
Richard Smithd3b5c9082012-07-27 04:22:15 +000012429void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12430 const CXXRecordDecl *RD) {
12431 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12432 E = RD->method_end(); I != E; ++I)
12433 if ((*I)->isVirtual() && !(*I)->isPure())
12434 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12435}
12436
Rafael Espindola5b334082010-03-26 00:36:59 +000012437void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12438 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012439 // Mark all functions which will appear in RD's vtable as used.
12440 CXXFinalOverriderMap FinalOverriders;
12441 RD->getFinalOverriders(FinalOverriders);
12442 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12443 E = FinalOverriders.end();
12444 I != E; ++I) {
12445 for (OverridingMethods::const_iterator OI = I->second.begin(),
12446 OE = I->second.end();
12447 OI != OE; ++OI) {
12448 assert(OI->second.size() > 0 && "no final overrider");
12449 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012450
Richard Smith4ff9ff92012-07-07 06:59:51 +000012451 // C++ [basic.def.odr]p2:
12452 // [...] A virtual member function is used if it is not pure. [...]
12453 if (!Overrider->isPure())
12454 MarkFunctionReferenced(Loc, Overrider);
12455 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012456 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012457
12458 // Only classes that have virtual bases need a VTT.
12459 if (RD->getNumVBases() == 0)
12460 return;
12461
12462 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12463 e = RD->bases_end(); i != e; ++i) {
12464 const CXXRecordDecl *Base =
12465 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012466 if (Base->getNumVBases() == 0)
12467 continue;
12468 MarkVirtualMembersReferenced(Loc, Base);
12469 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012470}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012471
12472/// SetIvarInitializers - This routine builds initialization ASTs for the
12473/// Objective-C implementation whose ivars need be initialized.
12474void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012475 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012476 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012477 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012478 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012479 CollectIvarsToConstructOrDestruct(OID, ivars);
12480 if (ivars.empty())
12481 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012482 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012483 for (unsigned i = 0; i < ivars.size(); i++) {
12484 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012485 if (Field->isInvalidDecl())
12486 continue;
12487
Alexis Hunt1d792652011-01-08 20:30:50 +000012488 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012489 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12490 InitializationKind InitKind =
12491 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012492
12493 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12494 ExprResult MemberInit =
12495 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012496 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012497 // Note, MemberInit could actually come back empty if no initialization
12498 // is required (e.g., because it would call a trivial default constructor)
12499 if (!MemberInit.get() || MemberInit.isInvalid())
12500 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012501
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012502 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012503 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12504 SourceLocation(),
12505 MemberInit.takeAs<Expr>(),
12506 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012507 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012508
12509 // Be sure that the destructor is accessible and is marked as referenced.
12510 if (const RecordType *RecordTy
12511 = Context.getBaseElementType(Field->getType())
12512 ->getAs<RecordType>()) {
12513 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012514 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012515 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012516 CheckDestructorAccess(Field->getLocation(), Destructor,
12517 PDiag(diag::err_access_dtor_ivar)
12518 << Context.getBaseElementType(Field->getType()));
12519 }
12520 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012521 }
12522 ObjCImplementation->setIvarInitializers(Context,
12523 AllToInit.data(), AllToInit.size());
12524 }
12525}
Alexis Hunt6118d662011-05-04 05:57:24 +000012526
Alexis Hunt27a761d2011-05-04 23:29:54 +000012527static
12528void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12529 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12530 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12531 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12532 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012533 if (Ctor->isInvalidDecl())
12534 return;
12535
Richard Smith802c4b72012-08-23 06:16:52 +000012536 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12537
12538 // Target may not be determinable yet, for instance if this is a dependent
12539 // call in an uninstantiated template.
12540 if (Target) {
12541 const FunctionDecl *FNTarget = 0;
12542 (void)Target->hasBody(FNTarget);
12543 Target = const_cast<CXXConstructorDecl*>(
12544 cast_or_null<CXXConstructorDecl>(FNTarget));
12545 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012546
12547 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12548 // Avoid dereferencing a null pointer here.
12549 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12550
12551 if (!Current.insert(Canonical))
12552 return;
12553
12554 // We know that beyond here, we aren't chaining into a cycle.
12555 if (!Target || !Target->isDelegatingConstructor() ||
12556 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012557 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012558 Current.clear();
12559 // We've hit a cycle.
12560 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12561 Current.count(TCanonical)) {
12562 // If we haven't diagnosed this cycle yet, do so now.
12563 if (!Invalid.count(TCanonical)) {
12564 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012565 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012566 << Ctor;
12567
Richard Smith802c4b72012-08-23 06:16:52 +000012568 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012569 if (TCanonical != Canonical)
12570 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12571
12572 CXXConstructorDecl *C = Target;
12573 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012574 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012575 (void)C->getTargetConstructor()->hasBody(FNTarget);
12576 assert(FNTarget && "Ctor cycle through bodiless function");
12577
Richard Smith802c4b72012-08-23 06:16:52 +000012578 C = const_cast<CXXConstructorDecl*>(
12579 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012580 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12581 }
12582 }
12583
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012584 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012585 Current.clear();
12586 } else {
12587 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12588 }
12589}
12590
12591
Alexis Hunt6118d662011-05-04 05:57:24 +000012592void Sema::CheckDelegatingCtorCycles() {
12593 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12594
Douglas Gregorbae31202011-07-27 21:57:17 +000012595 for (DelegatingCtorDeclsType::iterator
12596 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012597 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012598 I != E; ++I)
12599 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012600
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012601 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12602 CE = Invalid.end();
12603 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012604 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012605}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012606
Douglas Gregor3024f072012-04-16 07:05:22 +000012607namespace {
12608 /// \brief AST visitor that finds references to the 'this' expression.
12609 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12610 Sema &S;
12611
12612 public:
12613 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12614
12615 bool VisitCXXThisExpr(CXXThisExpr *E) {
12616 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12617 << E->isImplicit();
12618 return false;
12619 }
12620 };
12621}
12622
12623bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12624 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12625 if (!TSInfo)
12626 return false;
12627
12628 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012629 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012630 if (!ProtoTL)
12631 return false;
12632
12633 // C++11 [expr.prim.general]p3:
12634 // [The expression this] shall not appear before the optional
12635 // cv-qualifier-seq and it shall not appear within the declaration of a
12636 // static member function (although its type and value category are defined
12637 // within a static member function as they are within a non-static member
12638 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012639 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012640 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012641 FindCXXThisExpr Finder(*this);
12642
12643 // If the return type came after the cv-qualifier-seq, check it now.
12644 if (Proto->hasTrailingReturn() &&
David Blaikie6adc78e2013-02-18 22:06:02 +000012645 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012646 return true;
12647
12648 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012649 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12650 return true;
12651
12652 return checkThisInStaticMemberFunctionAttributes(Method);
12653}
12654
12655bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12656 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12657 if (!TSInfo)
12658 return false;
12659
12660 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012661 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012662 if (!ProtoTL)
12663 return false;
12664
David Blaikie6adc78e2013-02-18 22:06:02 +000012665 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012666 FindCXXThisExpr Finder(*this);
12667
Douglas Gregor3024f072012-04-16 07:05:22 +000012668 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012669 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012670 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012671 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012672 case EST_DynamicNone:
12673 case EST_MSAny:
12674 case EST_None:
12675 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012676
Douglas Gregor3024f072012-04-16 07:05:22 +000012677 case EST_ComputedNoexcept:
12678 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12679 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012680
Douglas Gregor3024f072012-04-16 07:05:22 +000012681 case EST_Dynamic:
12682 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012683 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012684 E != EEnd; ++E) {
12685 if (!Finder.TraverseType(*E))
12686 return true;
12687 }
12688 break;
12689 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012690
12691 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012692}
12693
12694bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12695 FindCXXThisExpr Finder(*this);
12696
12697 // Check attributes.
12698 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12699 A != AEnd; ++A) {
12700 // FIXME: This should be emitted by tblgen.
12701 Expr *Arg = 0;
12702 ArrayRef<Expr *> Args;
12703 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12704 Arg = G->getArg();
12705 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12706 Arg = G->getArg();
12707 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12708 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12709 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12710 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12711 else if (ExclusiveLockFunctionAttr *ELF
12712 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12713 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12714 else if (SharedLockFunctionAttr *SLF
12715 = dyn_cast<SharedLockFunctionAttr>(*A))
12716 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12717 else if (ExclusiveTrylockFunctionAttr *ETLF
12718 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12719 Arg = ETLF->getSuccessValue();
12720 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12721 } else if (SharedTrylockFunctionAttr *STLF
12722 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12723 Arg = STLF->getSuccessValue();
12724 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12725 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12726 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12727 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12728 Arg = LR->getArg();
12729 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12730 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12731 else if (ExclusiveLocksRequiredAttr *ELR
12732 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12733 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12734 else if (SharedLocksRequiredAttr *SLR
12735 = dyn_cast<SharedLocksRequiredAttr>(*A))
12736 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12737
12738 if (Arg && !Finder.TraverseStmt(Arg))
12739 return true;
12740
12741 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12742 if (!Finder.TraverseStmt(Args[I]))
12743 return true;
12744 }
12745 }
12746
12747 return false;
12748}
12749
Douglas Gregor433e0532012-04-16 18:27:27 +000012750void
12751Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12752 ArrayRef<ParsedType> DynamicExceptions,
12753 ArrayRef<SourceRange> DynamicExceptionRanges,
12754 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012755 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012756 FunctionProtoType::ExtProtoInfo &EPI) {
12757 Exceptions.clear();
12758 EPI.ExceptionSpecType = EST;
12759 if (EST == EST_Dynamic) {
12760 Exceptions.reserve(DynamicExceptions.size());
12761 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12762 // FIXME: Preserve type source info.
12763 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12764
12765 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12766 collectUnexpandedParameterPacks(ET, Unexpanded);
12767 if (!Unexpanded.empty()) {
12768 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12769 UPPC_ExceptionType,
12770 Unexpanded);
12771 continue;
12772 }
12773
12774 // Check that the type is valid for an exception spec, and
12775 // drop it if not.
12776 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12777 Exceptions.push_back(ET);
12778 }
12779 EPI.NumExceptions = Exceptions.size();
12780 EPI.Exceptions = Exceptions.data();
12781 return;
12782 }
12783
12784 if (EST == EST_ComputedNoexcept) {
12785 // If an error occurred, there's no expression here.
12786 if (NoexceptExpr) {
12787 assert((NoexceptExpr->isTypeDependent() ||
12788 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12789 Context.BoolTy) &&
12790 "Parser should have made sure that the expression is boolean");
12791 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12792 EPI.ExceptionSpecType = EST_BasicNoexcept;
12793 return;
12794 }
12795
12796 if (!NoexceptExpr->isValueDependent())
12797 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012798 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012799 /*AllowFold*/ false).take();
12800 EPI.NoexceptExpr = NoexceptExpr;
12801 }
12802 return;
12803 }
12804}
12805
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012806/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12807Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12808 // Implicitly declared functions (e.g. copy constructors) are
12809 // __host__ __device__
12810 if (D->isImplicit())
12811 return CFT_HostDevice;
12812
12813 if (D->hasAttr<CUDAGlobalAttr>())
12814 return CFT_Global;
12815
12816 if (D->hasAttr<CUDADeviceAttr>()) {
12817 if (D->hasAttr<CUDAHostAttr>())
12818 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012819 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012820 }
12821
12822 return CFT_Host;
12823}
12824
12825bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12826 CUDAFunctionTarget CalleeTarget) {
12827 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12828 // Callable from the device only."
12829 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12830 return true;
12831
12832 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12833 // Callable from the host only."
12834 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12835 // Callable from the host only."
12836 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12837 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12838 return true;
12839
12840 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12841 return true;
12842
12843 return false;
12844}
John McCall5e77d762013-04-16 07:28:30 +000012845
12846/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12847///
12848MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12849 SourceLocation DeclStart,
12850 Declarator &D, Expr *BitWidth,
12851 InClassInitStyle InitStyle,
12852 AccessSpecifier AS,
12853 AttributeList *MSPropertyAttr) {
12854 IdentifierInfo *II = D.getIdentifier();
12855 if (!II) {
12856 Diag(DeclStart, diag::err_anonymous_property);
12857 return NULL;
12858 }
12859 SourceLocation Loc = D.getIdentifierLoc();
12860
12861 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12862 QualType T = TInfo->getType();
12863 if (getLangOpts().CPlusPlus) {
12864 CheckExtraCXXDefaultArguments(D);
12865
12866 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12867 UPPC_DataMemberType)) {
12868 D.setInvalidType();
12869 T = Context.IntTy;
12870 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12871 }
12872 }
12873
12874 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12875
12876 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12877 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12878 diag::err_invalid_thread)
12879 << DeclSpec::getSpecifierName(TSCS);
12880
12881 // Check to see if this name was declared as a member previously
12882 NamedDecl *PrevDecl = 0;
12883 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12884 LookupName(Previous, S);
12885 switch (Previous.getResultKind()) {
12886 case LookupResult::Found:
12887 case LookupResult::FoundUnresolvedValue:
12888 PrevDecl = Previous.getAsSingle<NamedDecl>();
12889 break;
12890
12891 case LookupResult::FoundOverloaded:
12892 PrevDecl = Previous.getRepresentativeDecl();
12893 break;
12894
12895 case LookupResult::NotFound:
12896 case LookupResult::NotFoundInCurrentInstantiation:
12897 case LookupResult::Ambiguous:
12898 break;
12899 }
12900
12901 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12902 // Maybe we will complain about the shadowed template parameter.
12903 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12904 // Just pretend that we didn't see the previous declaration.
12905 PrevDecl = 0;
12906 }
12907
12908 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12909 PrevDecl = 0;
12910
12911 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012912 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012913 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12914 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012915 ProcessDeclAttributes(TUScope, NewPD, D);
12916 NewPD->setAccess(AS);
12917
12918 if (NewPD->isInvalidDecl())
12919 Record->setInvalidDecl();
12920
12921 if (D.getDeclSpec().isModulePrivateSpecified())
12922 NewPD->setModulePrivate();
12923
12924 if (NewPD->isInvalidDecl() && PrevDecl) {
12925 // Don't introduce NewFD into scope; there's already something
12926 // with the same name in the same scope.
12927 } else if (II) {
12928 PushOnScopeChains(NewPD, S);
12929 } else
12930 Record->addDecl(NewPD);
12931
12932 return NewPD;
12933}