blob: 846aba897274f56af1c3a44f0b89c8371733e865 [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 Smith83d48342013-11-15 02:29:26 +0000883 if (!VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_no_init)
886 << isa<CXXConstructorDecl>(Dcl);
887 return false;
888 }
889 }
890 SemaRef.Diag(VD->getLocation(),
891 SemaRef.getLangOpts().CPlusPlus1y
892 ? diag::warn_cxx11_compat_constexpr_local_var
893 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000894 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000895 continue;
896 }
897
898 case Decl::NamespaceAlias:
899 case Decl::Function:
900 // These are disallowed in C++11 and permitted in C++1y. Allow them
901 // everywhere as an extension.
902 if (!Cxx1yLoc.isValid())
903 Cxx1yLoc = DS->getLocStart();
904 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000905
906 default:
907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908 << isa<CXXConstructorDecl>(Dcl);
909 return false;
910 }
911 }
912
913 return true;
914}
915
916/// Check that the given field is initialized within a constexpr constructor.
917///
918/// \param Dcl The constexpr constructor being checked.
919/// \param Field The field being checked. This may be a member of an anonymous
920/// struct or union nested within the class being checked.
921/// \param Inits All declarations, including anonymous struct/union members and
922/// indirect members, for which any initialization was provided.
923/// \param Diagnosed Set to true if an error is produced.
924static void CheckConstexprCtorInitializer(Sema &SemaRef,
925 const FunctionDecl *Dcl,
926 FieldDecl *Field,
927 llvm::SmallSet<Decl*, 16> &Inits,
928 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000929 if (Field->isInvalidDecl())
930 return;
931
Douglas Gregor556e5862011-10-10 17:22:13 +0000932 if (Field->isUnnamedBitfield())
933 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000934
935 if (Field->isAnonymousStructOrUnion() &&
936 Field->getType()->getAsCXXRecordDecl()->isEmpty())
937 return;
938
Richard Smitheb3c10c2011-10-01 02:31:28 +0000939 if (!Inits.count(Field)) {
940 if (!Diagnosed) {
941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942 Diagnosed = true;
943 }
944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945 } else if (Field->isAnonymousStructOrUnion()) {
946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948 I != E; ++I)
949 // If an anonymous union contains an anonymous struct of which any member
950 // is initialized, all members must be initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000951 if (!RD->isUnion() || Inits.count(*I))
952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000953 }
954}
955
Richard Smithd9f663b2013-04-22 15:31:51 +0000956/// Check the provided statement is allowed in a constexpr function
957/// definition.
958static bool
959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000960 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000961 SourceLocation &Cxx1yLoc) {
962 // - its function-body shall be [...] a compound-statement that contains only
963 switch (S->getStmtClass()) {
964 case Stmt::NullStmtClass:
965 // - null statements,
966 return true;
967
968 case Stmt::DeclStmtClass:
969 // - static_assert-declarations
970 // - using-declarations,
971 // - using-directives,
972 // - typedef declarations and alias-declarations that do not define
973 // classes or enumerations,
974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975 return false;
976 return true;
977
978 case Stmt::ReturnStmtClass:
979 // - and exactly one return statement;
980 if (isa<CXXConstructorDecl>(Dcl)) {
981 // C++1y allows return statements in constexpr constructors.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984 return true;
985 }
986
987 ReturnStmts.push_back(S->getLocStart());
988 return true;
989
990 case Stmt::CompoundStmtClass: {
991 // C++1y allows compound-statements.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994
995 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999 Cxx1yLoc))
1000 return false;
1001 }
1002 return true;
1003 }
1004
1005 case Stmt::AttributedStmtClass:
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009
1010 case Stmt::IfStmtClass: {
1011 // C++1y allows if-statements.
1012 if (!Cxx1yLoc.isValid())
1013 Cxx1yLoc = S->getLocStart();
1014
1015 IfStmt *If = cast<IfStmt>(S);
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017 Cxx1yLoc))
1018 return false;
1019 if (If->getElse() &&
1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021 Cxx1yLoc))
1022 return false;
1023 return true;
1024 }
1025
1026 case Stmt::WhileStmtClass:
1027 case Stmt::DoStmtClass:
1028 case Stmt::ForStmtClass:
1029 case Stmt::CXXForRangeStmtClass:
1030 case Stmt::ContinueStmtClass:
1031 // C++1y allows all of these. We don't allow them as extensions in C++11,
1032 // because they don't make sense without variable mutation.
1033 if (!SemaRef.getLangOpts().CPlusPlus1y)
1034 break;
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037 for (Stmt::child_range Children = S->children(); Children; ++Children)
1038 if (*Children &&
1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 return true;
1043
1044 case Stmt::SwitchStmtClass:
1045 case Stmt::CaseStmtClass:
1046 case Stmt::DefaultStmtClass:
1047 case Stmt::BreakStmtClass:
1048 // C++1y allows switch-statements, and since they don't need variable
1049 // mutation, we can reasonably allow them in C++11 as an extension.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052 for (Stmt::child_range Children = S->children(); Children; ++Children)
1053 if (*Children &&
1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055 Cxx1yLoc))
1056 return false;
1057 return true;
1058
1059 default:
1060 if (!isa<Expr>(S))
1061 break;
1062
1063 // C++1y allows expression-statements.
1064 if (!Cxx1yLoc.isValid())
1065 Cxx1yLoc = S->getLocStart();
1066 return true;
1067 }
1068
1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070 << isa<CXXConstructorDecl>(Dcl);
1071 return false;
1072}
1073
Richard Smitheb3c10c2011-10-01 02:31:28 +00001074/// Check the body for the given constexpr function declaration only contains
1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076///
1077/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001079 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001081 // The definition of a constexpr function shall satisfy the following
1082 // constraints: [...]
1083 // - its function-body shall be = delete, = default, or a
1084 // compound-statement
1085 //
Richard Smith74388b42012-02-04 00:33:54 +00001086 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001087 // In the definition of a constexpr constructor, [...]
1088 // - its function-body shall not be a function-try-block;
1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090 << isa<CXXConstructorDecl>(Dcl);
1091 return false;
1092 }
1093
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001094 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001095
1096 // - its function-body shall be [...] a compound-statement that contains only
1097 // [... list of cases ...]
1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099 SourceLocation Cxx1yLoc;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 }
1105
Richard Smithd9f663b2013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smitheb3c10c2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
1119 // - if the class is a non-empty union, or for each non-empty anonymous
1120 // union member of a non-union class, exactly one non-static data member
1121 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smith4d59eeb2012-02-09 06:40:58 +00001123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125 return false;
1126 }
Richard Smithf368fb42011-10-10 16:38:04 +00001127 } else if (!Constructor->isDependentContext() &&
1128 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130
1131 // Skip detailed checking if we have enough initializers, and we would
1132 // allow at most one initializer per member.
1133 bool AnyAnonStructUnionMembers = false;
1134 unsigned Fields = 0;
1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001137 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 AnyAnonStructUnionMembers = true;
1139 break;
1140 }
1141 }
1142 if (AnyAnonStructUnionMembers ||
1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144 // Check initialization of non-static data members. Base classes are
1145 // always initialized so do not need to be checked. Dependent bases
1146 // might not have initializers in the member initializer list.
1147 llvm::SmallSet<Decl*, 16> Inits;
1148 for (CXXConstructorDecl::init_const_iterator
1149 I = Constructor->init_begin(), E = Constructor->init_end();
1150 I != E; ++I) {
1151 if (FieldDecl *FD = (*I)->getMember())
1152 Inits.insert(FD);
1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154 Inits.insert(ID->chain_begin(), ID->chain_end());
1155 }
1156
1157 bool Diagnosed = false;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001161 if (Diagnosed)
1162 return false;
1163 }
1164 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 } else {
1166 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001167 // C++1y doesn't require constexpr functions to contain a 'return'
1168 // statement. We still do, unless the return type is void, because
1169 // otherwise if there's no return statement, the function cannot
1170 // be used in a core constant expression.
Richard Smith3da88fa2013-04-26 14:36:30 +00001171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001172 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174 : diag::err_constexpr_body_no_return);
1175 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001176 }
1177 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001178 Diag(ReturnStmts.back(),
1179 getLangOpts().CPlusPlus1y
1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 }
1185 }
1186
Richard Smith74388b42012-02-04 00:33:54 +00001187 // C++11 [dcl.constexpr]p5:
1188 // if no function argument values exist such that the function invocation
1189 // substitution would produce a constant expression, the program is
1190 // ill-formed; no diagnostic required.
1191 // C++11 [dcl.constexpr]p3:
1192 // - every constructor call and implicit conversion used in initializing the
1193 // return value shall be one of those allowed in a constant expression.
1194 // C++11 [dcl.constexpr]p4:
1195 // - every constructor involved in initializing non-static data members and
1196 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001197 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001200 << isa<CXXConstructorDecl>(Dcl);
1201 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001203 // Don't return false here: we allow this for compatibility in
1204 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001205 }
1206
Richard Smitheb3c10c2011-10-01 02:31:28 +00001207 return true;
1208}
1209
Douglas Gregor61956c42008-10-31 09:07:45 +00001210/// isCurrentClassName - Determine whether the identifier II is the
1211/// name of the class type currently being defined. In the case of
1212/// nested classes, this will only return true if II is the name of
1213/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001216 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001217
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001218 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001219 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001220 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222 } else
1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001225 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001226 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001227 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001228}
1229
Richard Smithfb8b7b92013-10-15 00:00:26 +00001230/// \brief Determine whether the identifier II is a typo for the name of
1231/// the class type currently being defined. If so, update it to the identifier
1232/// that should have been used.
1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234 assert(getLangOpts().CPlusPlus && "No class names in C!");
1235
1236 if (!getLangOpts().SpellChecking)
1237 return false;
1238
1239 CXXRecordDecl *CurDecl;
1240 if (SS && SS->isSet() && !SS->isInvalid()) {
1241 DeclContext *DC = computeDeclContext(*SS, true);
1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248 < II->getLength()) {
1249 II = CurDecl->getIdentifier();
1250 return true;
1251 }
1252
1253 return false;
1254}
1255
Douglas Gregordc974572012-11-10 07:24:09 +00001256/// \brief Determine whether the given class is a base class of the given
1257/// class, including looking at dependent bases.
1258static bool findCircularInheritance(const CXXRecordDecl *Class,
1259 const CXXRecordDecl *Current) {
1260 SmallVector<const CXXRecordDecl*, 8> Queue;
1261
1262 Class = Class->getCanonicalDecl();
1263 while (true) {
1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265 E = Current->bases_end();
1266 I != E; ++I) {
1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001288}
1289
Mike Stump11289f42009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor463421d2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregor752a5952011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregor62004702012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump11289f42009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001341 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001362 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001363 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001364
Eli Friedmanc96d4962009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001372
David Majnemer9b1754d2013-11-02 12:00:36 +00001373 // A class which contains a flexible array member is not suitable for use as a
1374 // base class:
1375 // - If the layout determines that a base comes before another base,
1376 // the flexible array member would index into the subsequent base.
1377 // - If the layout determines that base comes before the derived class,
1378 // the flexible array member would index into the derived class.
1379 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
Anders Carlsson65c76d32011-03-25 14:55:14 +00001385 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001386 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001387 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001388 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001389 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001390 << CXXBaseDecl->getDeclName()
1391 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001392 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393 << CXXBaseDecl->getDeclName();
1394 return 0;
1395 }
1396
John McCall3696dcb2010-08-17 07:23:57 +00001397 if (BaseDecl->isInvalidDecl())
1398 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001399
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001400 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001404}
1405
Douglas Gregor556877c2008-04-13 21:30:24 +00001406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001408/// example:
1409/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001410/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001411BaseResult
John McCall48871652010-08-21 09:40:31 +00001412Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001413 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001414 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 ParsedType basetype, SourceLocation BaseLoc,
1416 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001417 if (!classdecl)
1418 return true;
1419
Douglas Gregorc40290e2009-03-09 23:48:35 +00001420 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001421 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001422 if (!Class)
1423 return true;
1424
Richard Smith4c96e992013-02-19 23:47:15 +00001425 // We do not support any C++11 attributes on base-specifiers yet.
1426 // Diagnose any attributes we see.
1427 if (!Attributes.empty()) {
1428 for (AttributeList *Attr = Attributes.getList(); Attr;
1429 Attr = Attr->getNext()) {
1430 if (Attr->isInvalid() ||
1431 Attr->getKind() == AttributeList::IgnoredAttribute)
1432 continue;
1433 Diag(Attr->getLoc(),
1434 Attr->getKind() == AttributeList::UnknownAttribute
1435 ? diag::warn_unknown_attribute_ignored
1436 : diag::err_base_specifier_attribute)
1437 << Attr->getName();
1438 }
1439 }
1440
Nick Lewycky19b9f952010-07-26 16:56:01 +00001441 TypeSourceInfo *TInfo = 0;
1442 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001443
Douglas Gregor752a5952011-01-03 22:36:02 +00001444 if (EllipsisLoc.isInvalid() &&
1445 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001446 UPPC_BaseType))
1447 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001448
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001450 Virtual, Access, TInfo,
1451 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001452 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001453 else
1454 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor463421d2009-03-03 04:44:36 +00001456 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001457}
Douglas Gregor556877c2008-04-13 21:30:24 +00001458
Douglas Gregor463421d2009-03-03 04:44:36 +00001459/// \brief Performs the actual work of attaching the given base class
1460/// specifiers to a C++ class.
1461bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462 unsigned NumBases) {
1463 if (NumBases == 0)
1464 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001465
1466 // Used to keep track of which base types we have already seen, so
1467 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001468 // that the key is always the unqualified canonical type of the base
1469 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001470 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471
1472 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001473 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001474 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001475 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001477 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001478 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001479
1480 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 // C++ [class.mi]p3:
1483 // A class shall not be specified as a direct base class of a
1484 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001485 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001486 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001487 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001488 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001489
1490 // Delete the duplicate base class specifier; we're going to
1491 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001492 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001493
1494 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001495 } else {
1496 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001497 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001498 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001499 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501 if (Class->isInterface() &&
1502 (!RD->isInterface() ||
1503 KnownBase->getAccessSpecifier() != AS_public)) {
1504 // The Microsoft extension __interface does not permit bases that
1505 // are not themselves public interfaces.
1506 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508 << RD->getSourceRange();
1509 Invalid = true;
1510 }
1511 if (RD->hasAttr<WeakAttr>())
1512 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1513 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001514 }
1515 }
1516
1517 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001518 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001519
1520 // Delete the remaining (good) base class specifiers, since their
1521 // data has been copied into the CXXRecordDecl.
1522 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001523 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001524
1525 return Invalid;
1526}
1527
1528/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529/// class, after checking whether there are any duplicate base
1530/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001531void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 unsigned NumBases) {
1533 if (!ClassDecl || !Bases || !NumBases)
1534 return;
1535
1536 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001537 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001538}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001539
Douglas Gregor36d1b142009-10-06 17:59:45 +00001540/// \brief Determine whether the type \p Derived is a C++ class that is
1541/// derived from the type \p Base.
1542bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001543 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001544 return false;
John McCalle78aac42010-03-10 03:28:59 +00001545
Douglas Gregor45bb4832013-03-26 23:36:30 +00001546 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001547 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001548 return false;
1549
Douglas Gregor45bb4832013-03-26 23:36:30 +00001550 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001551 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001553
1554 // If either the base or the derived type is invalid, don't try to
1555 // check whether one is derived from the other.
1556 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557 return false;
1558
John McCall67da35c2010-02-04 22:26:26 +00001559 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1560 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001561}
1562
1563/// \brief Determine whether the type \p Derived is a C++ class that is
1564/// derived from the type \p Base.
1565bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001566 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001567 return false;
1568
Douglas Gregor45bb4832013-03-26 23:36:30 +00001569 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001570 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001571 return false;
1572
Douglas Gregor45bb4832013-03-26 23:36:30 +00001573 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001574 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregor36d1b142009-10-06 17:59:45 +00001577 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578}
1579
Anders Carlssona70cff62010-04-24 19:06:50 +00001580void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001581 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001582 assert(BasePathArray.empty() && "Base path array must be empty!");
1583 assert(Paths.isRecordingPaths() && "Must record paths!");
1584
1585 const CXXBasePath &Path = Paths.front();
1586
1587 // We first go backward and check if we have a virtual base.
1588 // FIXME: It would be better if CXXBasePath had the base specifier for
1589 // the nearest virtual base.
1590 unsigned Start = 0;
1591 for (unsigned I = Path.size(); I != 0; --I) {
1592 if (Path[I - 1].Base->isVirtual()) {
1593 Start = I - 1;
1594 break;
1595 }
1596 }
1597
1598 // Now add all bases.
1599 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001600 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001601}
1602
Douglas Gregor88d292c2010-05-13 16:44:06 +00001603/// \brief Determine whether the given base path includes a virtual
1604/// base class.
John McCallcf142162010-08-07 06:22:56 +00001605bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606 for (CXXCastPath::const_iterator B = BasePath.begin(),
1607 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001608 B != BEnd; ++B)
1609 if ((*B)->isVirtual())
1610 return true;
1611
1612 return false;
1613}
1614
Douglas Gregor36d1b142009-10-06 17:59:45 +00001615/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616/// conversion (where Derived and Base are class types) is
1617/// well-formed, meaning that the conversion is unambiguous (and
1618/// that all of the base classes are accessible). Returns true
1619/// and emits a diagnostic if the code is ill-formed, returns false
1620/// otherwise. Loc is the location where this routine should point to
1621/// if there is an error, and Range is the source range to highlight
1622/// if there is an error.
1623bool
1624Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001625 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001626 unsigned AmbigiousBaseConvID,
1627 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001628 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001629 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001630 // First, determine whether the path from Derived to Base is
1631 // ambiguous. This is slightly more expensive than checking whether
1632 // the Derived to Base conversion exists, because here we need to
1633 // explore multiple paths to determine if there is an ambiguity.
1634 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635 /*DetectVirtual=*/false);
1636 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637 assert(DerivationOkay &&
1638 "Can only be used with a derived-to-base conversion");
1639 (void)DerivationOkay;
1640
1641 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001642 if (InaccessibleBaseID) {
1643 // Check that the base class can be accessed.
1644 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645 InaccessibleBaseID)) {
1646 case AR_inaccessible:
1647 return true;
1648 case AR_accessible:
1649 case AR_dependent:
1650 case AR_delayed:
1651 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001652 }
John McCall5b0829a2010-02-10 09:31:12 +00001653 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001654
1655 // Build a base path if necessary.
1656 if (BasePath)
1657 BuildBasePathArray(Paths, *BasePath);
1658 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001659 }
1660
David Majnemer626032f2013-06-22 06:43:58 +00001661 if (AmbigiousBaseConvID) {
1662 // We know that the derived-to-base conversion is ambiguous, and
1663 // we're going to produce a diagnostic. Perform the derived-to-base
1664 // search just one more time to compute all of the possible paths so
1665 // that we can print them out. This is more expensive than any of
1666 // the previous derived-to-base checks we've done, but at this point
1667 // performance isn't as much of an issue.
1668 Paths.clear();
1669 Paths.setRecordingPaths(true);
1670 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672 (void)StillOkay;
1673
1674 // Build up a textual representation of the ambiguous paths, e.g.,
1675 // D -> B -> A, that will be used to illustrate the ambiguous
1676 // conversions in the diagnostic. We only print one of the paths
1677 // to each base class subobject.
1678 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679
1680 Diag(Loc, AmbigiousBaseConvID)
1681 << Derived << Base << PathDisplayStr << Range << Name;
1682 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001683 return true;
1684}
1685
1686bool
1687Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001688 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001689 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001690 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001692 IgnoreAccess ? 0
1693 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001694 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001695 Loc, Range, DeclarationName(),
1696 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697}
1698
1699
1700/// @brief Builds a string representing ambiguous paths from a
1701/// specific derived class to different subobjects of the same base
1702/// class.
1703///
1704/// This function builds a string that can be used in error messages
1705/// to show the different paths that one can take through the
1706/// inheritance hierarchy to go from the derived class to different
1707/// subobjects of a base class. The result looks something like this:
1708/// @code
1709/// struct D -> struct B -> struct A
1710/// struct D -> struct C -> struct A
1711/// @endcode
1712std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713 std::string PathDisplayStr;
1714 std::set<unsigned> DisplayedPaths;
1715 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716 Path != Paths.end(); ++Path) {
1717 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718 // We haven't displayed a path to this particular base
1719 // class subobject yet.
1720 PathDisplayStr += "\n ";
1721 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722 for (CXXBasePath::const_iterator Element = Path->begin();
1723 Element != Path->end(); ++Element)
1724 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725 }
1726 }
1727
1728 return PathDisplayStr;
1729}
1730
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001731//===----------------------------------------------------------------------===//
1732// C++ class member Handling
1733//===----------------------------------------------------------------------===//
1734
Abramo Bagnarad7340582010-06-05 05:09:32 +00001735/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001736bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737 SourceLocation ASLoc,
1738 SourceLocation ColonLoc,
1739 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001740 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001741 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001742 ASLoc, ColonLoc);
1743 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001744 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745}
1746
Richard Smith18f07db2012-08-06 03:25:17 +00001747/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001748void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001749 if (D->isInvalidDecl())
1750 return;
1751
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001752 // We only care about "override" and "final" declarations.
1753 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001755
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001756 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001757
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001758 // We can't check dependent instance methods.
1759 if (MD && MD->isInstance() &&
1760 (MD->getParent()->hasAnyDependentBases() ||
1761 MD->getType()->isDependentType()))
1762 return;
1763
1764 if (MD && !MD->isVirtual()) {
1765 // If we have a non-virtual method, check if if hides a virtual method.
1766 // (In that case, it's most likely the method has the wrong type.)
1767 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768 FindHiddenVirtualMethods(MD, OverloadedMethods);
1769
1770 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001771 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001773 diag::override_keyword_hides_virtual_member_function)
1774 << "override" << (OverloadedMethods.size() > 1);
1775 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001776 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001777 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001778 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001780 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001781 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782 MD->setInvalidDecl();
1783 return;
1784 }
1785 // Fall through into the general case diagnostic.
1786 // FIXME: We might want to attempt typo correction here.
1787 }
1788
1789 if (!MD || !MD->isVirtual()) {
1790 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791 Diag(OA->getLocation(),
1792 diag::override_keyword_only_allowed_on_virtual_member_functions)
1793 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794 D->dropAttr<OverrideAttr>();
1795 }
1796 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797 Diag(FA->getLocation(),
1798 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001799 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001801 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001802 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001803 return;
1804 }
Richard Smith18f07db2012-08-06 03:25:17 +00001805
Richard Smith18f07db2012-08-06 03:25:17 +00001806 // C++11 [class.virtual]p5:
1807 // If a virtual function is marked with the virt-specifier override and
1808 // does not override a member function of a base class, the program is
1809 // ill-formed.
1810 bool HasOverriddenMethods =
1811 MD->begin_overridden_methods() != MD->end_overridden_methods();
1812 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001815}
1816
Richard Smith18f07db2012-08-06 03:25:17 +00001817/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001818/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001819/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001820bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001822 FinalAttr *FA = Old->getAttr<FinalAttr>();
1823 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001824 return false;
1825
1826 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001827 << New->getDeclName()
1828 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001831}
1832
Daniel Jasper0baec5492012-06-06 08:32:04 +00001833static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001834 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835 // FIXME: Destruction of ObjC lifetime types has side-effects.
1836 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837 return !RD->isCompleteDefinition() ||
1838 !RD->hasTrivialDefaultConstructor() ||
1839 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001840 return false;
1841}
1842
John McCall5e77d762013-04-16 07:28:30 +00001843static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844 for (AttributeList* it = list; it != 0; it = it->getNext())
1845 if (it->isDeclspecPropertyAttribute())
1846 return it;
1847 return 0;
1848}
1849
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001850/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001852/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001853/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001855NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001856Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001857 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001858 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001859 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001860 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001861 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862 DeclarationName Name = NameInfo.getName();
1863 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001864
1865 // For anonymous bitfields, the location should point to the type.
1866 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001867 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001868
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001869 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870
John McCallb1cd7da2010-06-04 08:34:12 +00001871 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001872 assert(!DS.isFriendSpecified());
1873
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001874 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001875
John McCalldb632ac2012-09-25 07:32:39 +00001876 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877 // The Microsoft extension __interface only permits public member functions
1878 // and prohibits constructors, destructors, operators, non-public member
1879 // functions, static methods and data members.
1880 unsigned InvalidDecl;
1881 bool ShowDeclName = true;
1882 if (!isFunc)
1883 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884 else if (AS != AS_public)
1885 InvalidDecl = 2;
1886 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887 InvalidDecl = 3;
1888 else switch (Name.getNameKind()) {
1889 case DeclarationName::CXXConstructorName:
1890 InvalidDecl = 4;
1891 ShowDeclName = false;
1892 break;
1893
1894 case DeclarationName::CXXDestructorName:
1895 InvalidDecl = 5;
1896 ShowDeclName = false;
1897 break;
1898
1899 case DeclarationName::CXXOperatorName:
1900 case DeclarationName::CXXConversionFunctionName:
1901 InvalidDecl = 6;
1902 break;
1903
1904 default:
1905 InvalidDecl = 0;
1906 break;
1907 }
1908
1909 if (InvalidDecl) {
1910 if (ShowDeclName)
1911 Diag(Loc, diag::err_invalid_member_in_interface)
1912 << (InvalidDecl-1) << Name;
1913 else
1914 Diag(Loc, diag::err_invalid_member_in_interface)
1915 << (InvalidDecl-1) << "";
1916 return 0;
1917 }
1918 }
1919
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001920 // C++ 9.2p6: A member shall not be declared to have automatic storage
1921 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001922 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923 // data members and cannot be applied to names declared const or static,
1924 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001926 case DeclSpec::SCS_unspecified:
1927 case DeclSpec::SCS_typedef:
1928 case DeclSpec::SCS_static:
1929 break;
1930 case DeclSpec::SCS_mutable:
1931 if (isFunc) {
1932 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Richard Smithb4a9e862013-04-12 22:46:28 +00001934 // FIXME: It would be nicer if the keyword was ignored only for this
1935 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001937 }
1938 break;
1939 default:
1940 Diag(DS.getStorageClassSpecLoc(),
1941 diag::err_storageclass_invalid_for_member);
1942 D.getMutableDeclSpec().ClearStorageClassSpecs();
1943 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944 }
1945
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001946 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001948 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001949
David Blaikie35506f82013-01-30 01:22:18 +00001950 if (DS.isConstexprSpecified() && isInstField) {
1951 SemaDiagnosticBuilder B =
1952 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954 if (InitStyle == ICIS_NoInit) {
1955 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956 D.getMutableDeclSpec().ClearConstexprSpec();
1957 const char *PrevSpec;
1958 unsigned DiagID;
1959 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001961 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001962 assert(!Failed && "Making a constexpr member const shouldn't fail");
1963 } else {
1964 B << 1;
1965 const char *PrevSpec;
1966 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001967 if (D.getMutableDeclSpec().SetStorageClassSpec(
1968 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001969 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001970 "This is the only DeclSpec that should fail to be applied");
1971 B << 1;
1972 } else {
1973 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1974 isInstField = false;
1975 }
1976 }
1977 }
1978
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001979 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001980 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001981 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001982
1983 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001984 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001985 Diag(Loc, diag::err_bad_variable_name)
1986 << Name;
1987 return 0;
1988 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001989
Benjamin Kramer365082d2012-05-19 16:34:46 +00001990 IdentifierInfo *II = Name.getAsIdentifierInfo();
1991
Douglas Gregor7c26c042011-09-21 14:40:46 +00001992 // Member field could not be with "template" keyword.
1993 // So TemplateParameterLists should be empty in this case.
1994 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001995 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00001996 if (TemplateParams->size()) {
1997 // There is no such thing as a member field template.
1998 Diag(D.getIdentifierLoc(), diag::err_template_member)
1999 << II
2000 << SourceRange(TemplateParams->getTemplateLoc(),
2001 TemplateParams->getRAngleLoc());
2002 } else {
2003 // There is an extraneous 'template<>' for this member.
2004 Diag(TemplateParams->getTemplateLoc(),
2005 diag::err_template_member_noparams)
2006 << II
2007 << SourceRange(TemplateParams->getTemplateLoc(),
2008 TemplateParams->getRAngleLoc());
2009 }
2010 return 0;
2011 }
2012
Douglas Gregora007d362010-10-13 22:19:53 +00002013 if (SS.isSet() && !SS.isInvalid()) {
2014 // The user provided a superfluous scope specifier inside a class
2015 // definition:
2016 //
2017 // class X {
2018 // int X::member;
2019 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002020 if (DeclContext *DC = computeDeclContext(SS, false))
2021 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002022 else
2023 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2024 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002025
Douglas Gregora007d362010-10-13 22:19:53 +00002026 SS.clear();
2027 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002028
John McCall5e77d762013-04-16 07:28:30 +00002029 AttributeList *MSPropertyAttr =
2030 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002031 if (MSPropertyAttr) {
2032 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2033 BitWidth, InitStyle, AS, MSPropertyAttr);
2034 if (!Member)
2035 return 0;
2036 isInstField = false;
2037 } else {
2038 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2039 BitWidth, InitStyle, AS);
2040 assert(Member && "HandleField never returns null");
2041 }
2042 } else {
2043 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2044
2045 Member = HandleDeclarator(S, D, TemplateParameterLists);
2046 if (!Member)
2047 return 0;
2048
2049 // Non-instance-fields can't have a bitfield.
2050 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002051 if (Member->isInvalidDecl()) {
2052 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002053 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002054 // C++ 9.6p3: A bit-field shall not be a static member.
2055 // "static member 'A' cannot be a bit-field"
2056 Diag(Loc, diag::err_static_not_bitfield)
2057 << Name << BitWidth->getSourceRange();
2058 } else if (isa<TypedefDecl>(Member)) {
2059 // "typedef member 'x' cannot be a bit-field"
2060 Diag(Loc, diag::err_typedef_not_bitfield)
2061 << Name << BitWidth->getSourceRange();
2062 } else {
2063 // A function typedef ("typedef int f(); f a;").
2064 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2065 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002066 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002067 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
Chris Lattnerd26760a2009-03-05 23:01:03 +00002070 BitWidth = 0;
2071 Member->setInvalidDecl();
2072 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002073
2074 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002075
Larisse Voufo39a1e502013-08-06 01:03:05 +00002076 // If we have declared a member function template or static data member
2077 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002078 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2079 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002080 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2081 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002082 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002083
Richard Smith18f07db2012-08-06 03:25:17 +00002084 if (VS.isOverrideSpecified())
2085 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2086 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002087 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2088 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002089
Douglas Gregorf2f08062011-03-08 17:10:18 +00002090 if (VS.getLastLocation().isValid()) {
2091 // Update the end location of a method that has a virt-specifiers.
2092 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2093 MD->setRangeEnd(VS.getLastLocation());
2094 }
Richard Smith18f07db2012-08-06 03:25:17 +00002095
Anders Carlssonc87f8612011-01-20 06:29:02 +00002096 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002097
Douglas Gregor92751d42008-11-17 22:58:34 +00002098 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002099
Daniel Jasper0baec5492012-06-06 08:32:04 +00002100 if (isInstField) {
2101 FieldDecl *FD = cast<FieldDecl>(Member);
2102 FieldCollector->Add(FD);
2103
2104 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2105 FD->getLocation())
2106 != DiagnosticsEngine::Ignored) {
2107 // Remember all explicit private FieldDecls that have a name, no side
2108 // effects and are not part of a dependent type declaration.
2109 if (!FD->isImplicit() && FD->getDeclName() &&
2110 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002111 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002112 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002113 !InitializationHasSideEffects(*FD))
2114 UnusedPrivateFields.insert(FD);
2115 }
2116 }
2117
John McCall48871652010-08-21 09:40:31 +00002118 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002119}
2120
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002121namespace {
2122 class UninitializedFieldVisitor
2123 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2124 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002125 // List of Decls to generate a warning on. Also remove Decls that become
2126 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002127 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002128 // If non-null, add a note to the warning pointing back to the constructor.
2129 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002130 public:
2131 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002132 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002133 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002134 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002135 : Inherited(S.Context), S(S), Decls(Decls),
2136 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002137
Richard Trieufd687772013-09-16 20:46:50 +00002138 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002139 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2140 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002141
Richard Trieu1bc22c12013-09-13 03:20:53 +00002142 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2143 // or union.
2144 MemberExpr *FieldME = ME;
2145
2146 Expr *Base = ME;
2147 while (isa<MemberExpr>(Base)) {
2148 ME = cast<MemberExpr>(Base);
2149
2150 if (isa<VarDecl>(ME->getMemberDecl()))
2151 return;
2152
2153 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2154 if (!FD->isAnonymousStructOrUnion())
2155 FieldME = ME;
2156
2157 Base = ME->getBase();
2158 }
2159
Richard Trieufd687772013-09-16 20:46:50 +00002160 if (!isa<CXXThisExpr>(Base))
2161 return;
2162
Richard Trieu406e65c2013-09-20 03:03:06 +00002163 ValueDecl* FoundVD = FieldME->getMemberDecl();
2164
Richard Trieuef64e942013-10-25 00:56:00 +00002165 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002166 return;
2167
Richard Trieuef64e942013-10-25 00:56:00 +00002168 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002169
Richard Trieuef64e942013-10-25 00:56:00 +00002170 // Prevent double warnings on use of unbounded references.
2171 if (IsReference != CheckReferenceOnly)
2172 return;
2173
2174 unsigned diag = IsReference
2175 ? diag::warn_reference_field_is_uninit
2176 : diag::warn_field_is_uninit;
2177 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2178 if (Constructor)
2179 S.Diag(Constructor->getLocation(),
2180 diag::note_uninit_in_this_constructor)
2181 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2182
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002183 }
2184
2185 void HandleValue(Expr *E) {
2186 E = E->IgnoreParens();
2187
2188 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002189 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002190 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002191 }
2192
2193 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2194 HandleValue(CO->getTrueExpr());
2195 HandleValue(CO->getFalseExpr());
2196 return;
2197 }
2198
2199 if (BinaryConditionalOperator *BCO =
2200 dyn_cast<BinaryConditionalOperator>(E)) {
2201 HandleValue(BCO->getCommon());
2202 HandleValue(BCO->getFalseExpr());
2203 return;
2204 }
2205
2206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2207 switch (BO->getOpcode()) {
2208 default:
2209 return;
2210 case(BO_PtrMemD):
2211 case(BO_PtrMemI):
2212 HandleValue(BO->getLHS());
2213 return;
2214 case(BO_Comma):
2215 HandleValue(BO->getRHS());
2216 return;
2217 }
2218 }
2219 }
2220
Richard Trieu1bc22c12013-09-13 03:20:53 +00002221 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002222 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002223 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002224
2225 Inherited::VisitMemberExpr(ME);
2226 }
2227
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002228 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2229 if (E->getCastKind() == CK_LValueToRValue)
2230 HandleValue(E->getSubExpr());
2231
2232 Inherited::VisitImplicitCastExpr(E);
2233 }
2234
Richard Trieu1bc22c12013-09-13 03:20:53 +00002235 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002236 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002237 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2238 if (ICE->getCastKind() == CK_NoOp)
2239 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002240 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002241
2242 Inherited::VisitCXXConstructExpr(E);
2243 }
2244
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002245 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2246 Expr *Callee = E->getCallee();
2247 if (isa<MemberExpr>(Callee))
2248 HandleValue(Callee);
2249
2250 Inherited::VisitCXXMemberCallExpr(E);
2251 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002252
2253 void VisitBinaryOperator(BinaryOperator *E) {
2254 // If a field assignment is detected, remove the field from the
2255 // uninitiailized field set.
2256 if (E->getOpcode() == BO_Assign)
2257 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2258 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002259 if (!FD->getType()->isReferenceType())
2260 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002261
2262 Inherited::VisitBinaryOperator(E);
2263 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002264 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002265 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002266 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2267 const CXXConstructorDecl *Constructor) {
2268 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002269 return;
2270
Richard Trieuef64e942013-10-25 00:56:00 +00002271 if (!E)
2272 return;
2273
2274 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2275 E = Default->getExpr();
2276 if (!E)
2277 return;
2278 // In class initializers will point to the constructor.
2279 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2280 } else {
2281 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2282 }
2283 }
2284
2285 // Diagnose value-uses of fields to initialize themselves, e.g.
2286 // foo(foo)
2287 // where foo is not also a parameter to the constructor.
2288 // Also diagnose across field uninitialized use such as
2289 // x(y), y(x)
2290 // TODO: implement -Wuninitialized and fold this into that framework.
2291 static void DiagnoseUninitializedFields(
2292 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2293
2294 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2295 Constructor->getLocation())
2296 == DiagnosticsEngine::Ignored) {
2297 return;
2298 }
2299
2300 if (Constructor->isInvalidDecl())
2301 return;
2302
2303 const CXXRecordDecl *RD = Constructor->getParent();
2304
2305 // Holds fields that are uninitialized.
2306 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2307
2308 // At the beginning, all fields are uninitialized.
2309 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2310 I != E; ++I) {
2311 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2312 UninitializedFields.insert(FD);
2313 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2314 UninitializedFields.insert(IFD->getAnonField());
2315 }
2316 }
2317
2318 for (CXXConstructorDecl::init_const_iterator FieldInit =
2319 Constructor->init_begin(),
2320 FieldInitEnd = Constructor->init_end();
2321 FieldInit != FieldInitEnd; ++FieldInit) {
2322
2323 Expr *InitExpr = (*FieldInit)->getInit();
2324
2325 CheckInitExprContainsUninitializedFields(
2326 SemaRef, InitExpr, UninitializedFields, Constructor);
2327
2328 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2329 UninitializedFields.erase(Field);
2330 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002331 }
2332} // namespace
2333
Richard Smith938f40b2011-06-11 17:19:42 +00002334/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00002335/// in-class initializer for a non-static C++ class member, and after
2336/// instantiating an in-class initializer in a class template. Such actions
2337/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00002338void
Richard Smith2b013182012-06-10 03:12:00 +00002339Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith938f40b2011-06-11 17:19:42 +00002340 Expr *InitExpr) {
2341 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002342 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2343 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002344
2345 if (!InitExpr) {
2346 FD->setInvalidDecl();
2347 FD->removeInClassInitializer();
2348 return;
2349 }
2350
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002351 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2352 FD->setInvalidDecl();
2353 FD->removeInClassInitializer();
2354 return;
2355 }
2356
Richard Smith938f40b2011-06-11 17:19:42 +00002357 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002358 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002359 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002360 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002361 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002362 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002363 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2364 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002365 if (Init.isInvalid()) {
2366 FD->setInvalidDecl();
2367 return;
2368 }
Richard Smith938f40b2011-06-11 17:19:42 +00002369 }
2370
Richard Smith945f8d32013-01-14 22:39:08 +00002371 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002372 // The initialization of each base and member constitutes a
2373 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002374 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002375 if (Init.isInvalid()) {
2376 FD->setInvalidDecl();
2377 return;
2378 }
2379
2380 InitExpr = Init.release();
2381
2382 FD->setInClassInitializer(InitExpr);
2383}
2384
Douglas Gregor15e77a22009-12-31 09:10:24 +00002385/// \brief Find the direct and/or virtual base specifiers that
2386/// correspond to the given base type, for use in base initialization
2387/// within a constructor.
2388static bool FindBaseInitializer(Sema &SemaRef,
2389 CXXRecordDecl *ClassDecl,
2390 QualType BaseType,
2391 const CXXBaseSpecifier *&DirectBaseSpec,
2392 const CXXBaseSpecifier *&VirtualBaseSpec) {
2393 // First, check for a direct base class.
2394 DirectBaseSpec = 0;
2395 for (CXXRecordDecl::base_class_const_iterator Base
2396 = ClassDecl->bases_begin();
2397 Base != ClassDecl->bases_end(); ++Base) {
2398 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2399 // We found a direct base of this type. That's what we're
2400 // initializing.
2401 DirectBaseSpec = &*Base;
2402 break;
2403 }
2404 }
2405
2406 // Check for a virtual base class.
2407 // FIXME: We might be able to short-circuit this if we know in advance that
2408 // there are no virtual bases.
2409 VirtualBaseSpec = 0;
2410 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2411 // We haven't found a base yet; search the class hierarchy for a
2412 // virtual base class.
2413 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2414 /*DetectVirtual=*/false);
2415 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2416 BaseType, Paths)) {
2417 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2418 Path != Paths.end(); ++Path) {
2419 if (Path->back().Base->isVirtual()) {
2420 VirtualBaseSpec = Path->back().Base;
2421 break;
2422 }
2423 }
2424 }
2425 }
2426
2427 return DirectBaseSpec || VirtualBaseSpec;
2428}
2429
Sebastian Redla74948d2011-09-24 17:48:25 +00002430/// \brief Handle a C++ member initializer using braced-init-list syntax.
2431MemInitResult
2432Sema::ActOnMemInitializer(Decl *ConstructorD,
2433 Scope *S,
2434 CXXScopeSpec &SS,
2435 IdentifierInfo *MemberOrBase,
2436 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002437 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002438 SourceLocation IdLoc,
2439 Expr *InitList,
2440 SourceLocation EllipsisLoc) {
2441 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002442 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002443 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002444}
2445
2446/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002447MemInitResult
John McCall48871652010-08-21 09:40:31 +00002448Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002449 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002450 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002451 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002452 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002453 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002454 SourceLocation IdLoc,
2455 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002456 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002457 SourceLocation RParenLoc,
2458 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002459 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002460 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002461 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002462 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002463}
2464
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002465namespace {
2466
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002467// Callback to only accept typo corrections that can be a valid C++ member
2468// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002469class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002470public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002471 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2472 : ClassDecl(ClassDecl) {}
2473
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002474 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002475 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2476 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2477 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002478 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002479 }
2480 return false;
2481 }
2482
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002483private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002484 CXXRecordDecl *ClassDecl;
2485};
2486
2487}
2488
Sebastian Redla74948d2011-09-24 17:48:25 +00002489/// \brief Handle a C++ member initializer.
2490MemInitResult
2491Sema::BuildMemInitializer(Decl *ConstructorD,
2492 Scope *S,
2493 CXXScopeSpec &SS,
2494 IdentifierInfo *MemberOrBase,
2495 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002496 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002497 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002498 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002499 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002500 if (!ConstructorD)
2501 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002502
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002503 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002504
2505 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002506 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002507 if (!Constructor) {
2508 // The user wrote a constructor initializer on a function that is
2509 // not a C++ constructor. Ignore the error for now, because we may
2510 // have more member initializers coming; we'll diagnose it just
2511 // once in ActOnMemInitializers.
2512 return true;
2513 }
2514
2515 CXXRecordDecl *ClassDecl = Constructor->getParent();
2516
2517 // C++ [class.base.init]p2:
2518 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002519 // constructor's class and, if not found in that scope, are looked
2520 // up in the scope containing the constructor's definition.
2521 // [Note: if the constructor's class contains a member with the
2522 // same name as a direct or virtual base class of the class, a
2523 // mem-initializer-id naming the member or base class and composed
2524 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002525 // mem-initializer-id for the hidden base class may be specified
2526 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002527 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002528 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002529 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002530 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002531 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002532 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002533 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2534 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002535 if (EllipsisLoc.isValid())
2536 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002537 << MemberOrBase
2538 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002539
Sebastian Redla9351792012-02-11 23:51:47 +00002540 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002541 }
Francois Pichetd583da02010-12-04 09:14:42 +00002542 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002543 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002544 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002545 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002546 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002547
2548 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002549 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002550 } else if (DS.getTypeSpecType() == TST_decltype) {
2551 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002552 } else {
2553 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2554 LookupParsedName(R, S, &SS);
2555
2556 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2557 if (!TyD) {
2558 if (R.isAmbiguous()) return true;
2559
John McCallda6841b2010-04-09 19:01:14 +00002560 // We don't want access-control diagnostics here.
2561 R.suppressDiagnostics();
2562
Douglas Gregora3b624a2010-01-19 06:46:48 +00002563 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2564 bool NotUnknownSpecialization = false;
2565 DeclContext *DC = computeDeclContext(SS, false);
2566 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2567 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2568
2569 if (!NotUnknownSpecialization) {
2570 // When the scope specifier can refer to a member of an unknown
2571 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002572 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2573 SS.getWithLocInContext(Context),
2574 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002575 if (BaseType.isNull())
2576 return true;
2577
Douglas Gregora3b624a2010-01-19 06:46:48 +00002578 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002579 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002580 }
2581 }
2582
Douglas Gregor15e77a22009-12-31 09:10:24 +00002583 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002584 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002585 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002586 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002587 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002588 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002589 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002590 // We have found a non-static data member with a similar
2591 // name to what was typed; complain and initialize that
2592 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002593 diagnoseTypo(Corr,
2594 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2595 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002596 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002597 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002598 const CXXBaseSpecifier *DirectBaseSpec;
2599 const CXXBaseSpecifier *VirtualBaseSpec;
2600 if (FindBaseInitializer(*this, ClassDecl,
2601 Context.getTypeDeclType(Type),
2602 DirectBaseSpec, VirtualBaseSpec)) {
2603 // We have found a direct or virtual base class with a
2604 // similar name to what was typed; complain and initialize
2605 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002606 diagnoseTypo(Corr,
2607 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608 << MemberOrBase << false,
2609 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002610
Richard Smithf9b15102013-08-17 00:46:16 +00002611 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2612 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002613 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002614 diag::note_base_class_specified_here)
2615 << BaseSpec->getType()
2616 << BaseSpec->getSourceRange();
2617
Douglas Gregor15e77a22009-12-31 09:10:24 +00002618 TyD = Type;
2619 }
2620 }
2621 }
2622
Douglas Gregora3b624a2010-01-19 06:46:48 +00002623 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002624 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002625 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002626 return true;
2627 }
John McCallb5a0d312009-12-21 10:41:20 +00002628 }
2629
Douglas Gregora3b624a2010-01-19 06:46:48 +00002630 if (BaseType.isNull()) {
2631 BaseType = Context.getTypeDeclType(TyD);
2632 if (SS.isSet()) {
2633 NestedNameSpecifier *Qualifier =
2634 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00002635
Douglas Gregora3b624a2010-01-19 06:46:48 +00002636 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00002637 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002638 }
John McCallb5a0d312009-12-21 10:41:20 +00002639 }
2640 }
Mike Stump11289f42009-09-09 15:08:12 +00002641
John McCallbcd03502009-12-07 02:54:59 +00002642 if (!TInfo)
2643 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002644
Sebastian Redla9351792012-02-11 23:51:47 +00002645 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002646}
2647
Chandler Carruth599deef2011-09-03 01:14:15 +00002648/// Checks a member initializer expression for cases where reference (or
2649/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002650static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2651 Expr *Init,
2652 SourceLocation IdLoc) {
2653 QualType MemberTy = Member->getType();
2654
2655 // We only handle pointers and references currently.
2656 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2657 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2658 return;
2659
2660 const bool IsPointer = MemberTy->isPointerType();
2661 if (IsPointer) {
2662 if (const UnaryOperator *Op
2663 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2664 // The only case we're worried about with pointers requires taking the
2665 // address.
2666 if (Op->getOpcode() != UO_AddrOf)
2667 return;
2668
2669 Init = Op->getSubExpr();
2670 } else {
2671 // We only handle address-of expression initializers for pointers.
2672 return;
2673 }
2674 }
2675
Richard Smithe3b28bc2013-06-12 21:51:50 +00002676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002677 // We only warn when referring to a non-reference parameter declaration.
2678 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2679 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002680 return;
2681
2682 S.Diag(Init->getExprLoc(),
2683 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2684 : diag::warn_bind_ref_member_to_parameter)
2685 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002686 } else {
2687 // Other initializers are fine.
2688 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002689 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002690
2691 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2692 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002693}
2694
John McCallfaf5fb42010-08-26 23:41:50 +00002695MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002696Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002697 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002698 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2699 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2700 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002701 "Member must be a FieldDecl or IndirectFieldDecl");
2702
Sebastian Redla9351792012-02-11 23:51:47 +00002703 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002704 return true;
2705
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002706 if (Member->isInvalidDecl())
2707 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002708
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002709 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002710 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002711 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002712 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002713 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002714 } else {
2715 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002716 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002717 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002718
Sebastian Redla9351792012-02-11 23:51:47 +00002719 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002720
Sebastian Redla9351792012-02-11 23:51:47 +00002721 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002722 // Can't check initialization for a member of dependent type or when
2723 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002724 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002725 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002726 bool InitList = false;
2727 if (isa<InitListExpr>(Init)) {
2728 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002729 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002730 }
2731
Chandler Carruthd44c3102010-12-06 09:23:57 +00002732 // Initialize the member.
2733 InitializedEntity MemberEntity =
2734 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2735 : InitializedEntity::InitializeMember(IndirectMember, 0);
2736 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002737 InitList ? InitializationKind::CreateDirectList(IdLoc)
2738 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2739 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002740
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002741 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2742 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002743 if (MemberInit.isInvalid())
2744 return true;
2745
Richard Smith736a9472013-06-12 20:42:33 +00002746 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2747
Richard Smith945f8d32013-01-14 22:39:08 +00002748 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002749 // The initialization of each base and member constitutes a
2750 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002751 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002752 if (MemberInit.isInvalid())
2753 return true;
2754
Richard Smithd59b8322012-12-19 01:39:02 +00002755 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002756 }
2757
Chandler Carruthd44c3102010-12-06 09:23:57 +00002758 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002759 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2760 InitRange.getBegin(), Init,
2761 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002762 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002763 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2764 InitRange.getBegin(), Init,
2765 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002766 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002767}
2768
John McCallfaf5fb42010-08-26 23:41:50 +00002769MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002770Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002771 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002772 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002773 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002774 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002775 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002776 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002777
Sebastian Redl0501c632012-02-12 16:37:36 +00002778 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002779 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002780 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2781 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002782 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002783 }
2784
Sebastian Redla9351792012-02-11 23:51:47 +00002785 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002786 // Initialize the object.
2787 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2788 QualType(ClassDecl->getTypeForDecl(), 0));
2789 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002790 InitList ? InitializationKind::CreateDirectList(NameLoc)
2791 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2792 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002793 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002794 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002795 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002796 if (DelegationInit.isInvalid())
2797 return true;
2798
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002799 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2800 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002801
Richard Smith945f8d32013-01-14 22:39:08 +00002802 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803 // The initialization of each base and member constitutes a
2804 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002805 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2806 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002807 if (DelegationInit.isInvalid())
2808 return true;
2809
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002810 // If we are in a dependent context, template instantiation will
2811 // perform this type-checking again. Just save the arguments that we
2812 // received in a ParenListExpr.
2813 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2814 // of the information that we have about the base
2815 // initializer. However, deconstructing the ASTs is a dicey process,
2816 // and this approach is far more likely to get the corner cases right.
2817 if (CurContext->isDependentContext())
2818 DelegationInit = Owned(Init);
2819
Sebastian Redla9351792012-02-11 23:51:47 +00002820 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002821 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002822 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002823}
2824
2825MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002826Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002827 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002828 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002829 SourceLocation BaseLoc
2830 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002831
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002832 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2833 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2834 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2835
2836 // C++ [class.base.init]p2:
2837 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002838 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002839 // of that class, the mem-initializer is ill-formed. A
2840 // mem-initializer-list can initialize a base class using any
2841 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002842 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002843
Sebastian Redla9351792012-02-11 23:51:47 +00002844 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002845 if (EllipsisLoc.isValid()) {
2846 // This is a pack expansion.
2847 if (!BaseType->containsUnexpandedParameterPack()) {
2848 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002849 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002850
Douglas Gregor44e7df62011-01-04 00:32:56 +00002851 EllipsisLoc = SourceLocation();
2852 }
2853 } else {
2854 // Check for any unexpanded parameter packs.
2855 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2856 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002857
Sebastian Redla9351792012-02-11 23:51:47 +00002858 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002859 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002860 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002861
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002862 // Check for direct and virtual base classes.
2863 const CXXBaseSpecifier *DirectBaseSpec = 0;
2864 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2865 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002866 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2867 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002868 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002869
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002870 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2871 VirtualBaseSpec);
2872
2873 // C++ [base.class.init]p2:
2874 // Unless the mem-initializer-id names a nonstatic data member of the
2875 // constructor's class or a direct or virtual base of that class, the
2876 // mem-initializer is ill-formed.
2877 if (!DirectBaseSpec && !VirtualBaseSpec) {
2878 // If the class has any dependent bases, then it's possible that
2879 // one of those types will resolve to the same type as
2880 // BaseType. Therefore, just treat this as a dependent base
2881 // class initialization. FIXME: Should we try to check the
2882 // initialization anyway? It seems odd.
2883 if (ClassDecl->hasAnyDependentBases())
2884 Dependent = true;
2885 else
2886 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2887 << BaseType << Context.getTypeDeclType(ClassDecl)
2888 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2889 }
2890 }
2891
2892 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002893 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002894
Sebastian Redla74948d2011-09-24 17:48:25 +00002895 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2896 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002897 InitRange.getBegin(), Init,
2898 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002899 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002900
2901 // C++ [base.class.init]p2:
2902 // If a mem-initializer-id is ambiguous because it designates both
2903 // a direct non-virtual base class and an inherited virtual base
2904 // class, the mem-initializer is ill-formed.
2905 if (DirectBaseSpec && VirtualBaseSpec)
2906 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002907 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002908
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002909 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002910 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002911 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002912
2913 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002914 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002915 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002916 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002917 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002918 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002919 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002920
2921 InitializedEntity BaseEntity =
2922 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2923 InitializationKind Kind =
2924 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2925 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2926 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002927 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2928 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002929 if (BaseInit.isInvalid())
2930 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002931
Richard Smith945f8d32013-01-14 22:39:08 +00002932 // C++11 [class.base.init]p7:
2933 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002934 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002935 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002936 if (BaseInit.isInvalid())
2937 return true;
2938
2939 // If we are in a dependent context, template instantiation will
2940 // perform this type-checking again. Just save the arguments that we
2941 // received in a ParenListExpr.
2942 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2943 // of the information that we have about the base
2944 // initializer. However, deconstructing the ASTs is a dicey process,
2945 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002946 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002947 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002948
Alexis Hunt1d792652011-01-08 20:30:50 +00002949 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002950 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002951 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002952 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002953 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002954}
2955
Sebastian Redl22653ba2011-08-30 19:58:05 +00002956// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002957static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2958 if (T.isNull()) T = E->getType();
2959 QualType TargetType = SemaRef.BuildReferenceType(
2960 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002961 SourceLocation ExprLoc = E->getLocStart();
2962 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2963 TargetType, ExprLoc);
2964
2965 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2966 SourceRange(ExprLoc, ExprLoc),
2967 E->getSourceRange()).take();
2968}
2969
Anders Carlsson1b00e242010-04-23 03:10:23 +00002970/// ImplicitInitializerKind - How an implicit base or member initializer should
2971/// initialize its base or member.
2972enum ImplicitInitializerKind {
2973 IIK_Default,
2974 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002975 IIK_Move,
2976 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002977};
2978
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002979static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002980BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002981 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002982 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002983 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002984 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002985 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002986 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2987 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002988
John McCalldadc5752010-08-24 06:29:42 +00002989 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002990
2991 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002992 case IIK_Inherit: {
2993 const CXXRecordDecl *Inherited =
2994 Constructor->getInheritedConstructor()->getParent();
2995 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2996 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2997 // C++11 [class.inhctor]p8:
2998 // Each expression in the expression-list is of the form
2999 // static_cast<T&&>(p), where p is the name of the corresponding
3000 // constructor parameter and T is the declared type of p.
3001 SmallVector<Expr*, 16> Args;
3002 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3003 ParmVarDecl *PD = Constructor->getParamDecl(I);
3004 ExprResult ArgExpr =
3005 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3006 VK_LValue, SourceLocation());
3007 if (ArgExpr.isInvalid())
3008 return true;
3009 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3010 }
3011
3012 InitializationKind InitKind = InitializationKind::CreateDirect(
3013 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003014 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003015 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3016 break;
3017 }
3018 }
3019 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003020 case IIK_Default: {
3021 InitializationKind InitKind
3022 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003023 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3024 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003025 break;
3026 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003027
Sebastian Redl22653ba2011-08-30 19:58:05 +00003028 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003029 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003030 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003031 ParmVarDecl *Param = Constructor->getParamDecl(0);
3032 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003033
Anders Carlsson1b00e242010-04-23 03:10:23 +00003034 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003035 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003036 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003037 Constructor->getLocation(), ParamType,
3038 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003039
Eli Friedmanfa0df832012-02-02 03:46:19 +00003040 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3041
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003042 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003043 QualType ArgTy =
3044 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3045 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003046
Sebastian Redl22653ba2011-08-30 19:58:05 +00003047 if (Moving) {
3048 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3049 }
3050
John McCallcf142162010-08-07 06:22:56 +00003051 CXXCastPath BasePath;
3052 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003053 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3054 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003055 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003056 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003057
Anders Carlsson1b00e242010-04-23 03:10:23 +00003058 InitializationKind InitKind
3059 = InitializationKind::CreateDirect(Constructor->getLocation(),
3060 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003061 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3062 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003063 break;
3064 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003065 }
John McCallb268a282010-08-23 23:25:46 +00003066
Douglas Gregora40433a2010-12-07 00:41:46 +00003067 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003068 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003069 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003070
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003071 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003072 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003073 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3074 SourceLocation()),
3075 BaseSpec->isVirtual(),
3076 SourceLocation(),
3077 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003078 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003079 SourceLocation());
3080
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003081 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003082}
3083
Sebastian Redl22653ba2011-08-30 19:58:05 +00003084static bool RefersToRValueRef(Expr *MemRef) {
3085 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3086 return Referenced->getType()->isRValueReferenceType();
3087}
3088
Anders Carlsson3c1db572010-04-23 02:15:47 +00003089static bool
3090BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003091 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003092 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003093 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003094 if (Field->isInvalidDecl())
3095 return true;
3096
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003097 SourceLocation Loc = Constructor->getLocation();
3098
Sebastian Redl22653ba2011-08-30 19:58:05 +00003099 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3100 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003101 ParmVarDecl *Param = Constructor->getParamDecl(0);
3102 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003103
3104 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003105 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3106 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003107
Anders Carlsson423f5d82010-04-23 16:04:08 +00003108 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003109 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003110 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003111 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003112
Eli Friedmanfa0df832012-02-02 03:46:19 +00003113 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3114
Sebastian Redl22653ba2011-08-30 19:58:05 +00003115 if (Moving) {
3116 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3117 }
3118
Douglas Gregor94f9a482010-05-05 05:51:00 +00003119 // Build a reference to this field within the parameter.
3120 CXXScopeSpec SS;
3121 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3122 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003123 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3124 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003125 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003126 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003127 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003128 ParamType, Loc,
3129 /*IsArrow=*/false,
3130 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003131 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003132 /*FirstQualifierInScope=*/0,
3133 MemberLookup,
3134 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003135 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003136 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003137
3138 // C++11 [class.copy]p15:
3139 // - if a member m has rvalue reference type T&&, it is direct-initialized
3140 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003141 if (RefersToRValueRef(CtorArg.get())) {
3142 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003143 }
3144
Douglas Gregor94f9a482010-05-05 05:51:00 +00003145 // When the field we are copying is an array, create index variables for
3146 // each dimension of the array. We use these index variables to subscript
3147 // the source array, and other clients (e.g., CodeGen) will perform the
3148 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003149 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003150 QualType BaseType = Field->getType();
3151 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003152 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003153 while (const ConstantArrayType *Array
3154 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003155 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003156 // Create the iteration variable for this array index.
3157 IdentifierInfo *IterationVarName = 0;
3158 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003159 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003160 llvm::raw_svector_ostream OS(Str);
3161 OS << "__i" << IndexVariables.size();
3162 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3163 }
3164 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003165 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003166 IterationVarName, SizeType,
3167 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003168 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003169 IndexVariables.push_back(IterationVar);
3170
3171 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003172 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003173 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003174 assert(!IterationVarRef.isInvalid() &&
3175 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003176 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3177 assert(!IterationVarRef.isInvalid() &&
3178 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003179
Douglas Gregor94f9a482010-05-05 05:51:00 +00003180 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003181 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003182 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003183 Loc);
3184 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003185 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003186
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 BaseType = Array->getElementType();
3188 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003189
3190 // The array subscript expression is an lvalue, which is wrong for moving.
3191 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003192 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003193
Douglas Gregor94f9a482010-05-05 05:51:00 +00003194 // Construct the entity that we will be initializing. For an array, this
3195 // will be first element in the array, which may require several levels
3196 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003197 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003198 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003199 if (Indirect)
3200 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3201 else
3202 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003203 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3204 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3205 0,
3206 Entities.back()));
3207
3208 // Direct-initialize to use the copy constructor.
3209 InitializationKind InitKind =
3210 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3211
Sebastian Redle9c4e842011-09-04 18:14:28 +00003212 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003213 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003214
John McCalldadc5752010-08-24 06:29:42 +00003215 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003216 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003217 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003218 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003219 if (MemberInit.isInvalid())
3220 return true;
3221
Douglas Gregor493627b2011-08-10 15:22:55 +00003222 if (Indirect) {
3223 assert(IndexVariables.size() == 0 &&
3224 "Indirect field improperly initialized");
3225 CXXMemberInit
3226 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3227 Loc, Loc,
3228 MemberInit.takeAs<Expr>(),
3229 Loc);
3230 } else
3231 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3232 Loc, MemberInit.takeAs<Expr>(),
3233 Loc,
3234 IndexVariables.data(),
3235 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003236 return false;
3237 }
3238
Richard Smithc2bc61b2013-03-18 21:12:30 +00003239 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3240 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003241
Anders Carlsson3c1db572010-04-23 02:15:47 +00003242 QualType FieldBaseElementType =
3243 SemaRef.Context.getBaseElementType(Field->getType());
3244
Anders Carlsson3c1db572010-04-23 02:15:47 +00003245 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003246 InitializedEntity InitEntity
3247 = Indirect? InitializedEntity::InitializeMember(Indirect)
3248 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003249 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003250 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003251
3252 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3253 ExprResult MemberInit =
3254 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003255
Douglas Gregora40433a2010-12-07 00:41:46 +00003256 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003257 if (MemberInit.isInvalid())
3258 return true;
3259
Douglas Gregor493627b2011-08-10 15:22:55 +00003260 if (Indirect)
3261 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3262 Indirect, Loc,
3263 Loc,
3264 MemberInit.get(),
3265 Loc);
3266 else
3267 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3268 Field, Loc, Loc,
3269 MemberInit.get(),
3270 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003271 return false;
3272 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003273
Alexis Hunt8b455182011-05-17 00:19:05 +00003274 if (!Field->getParent()->isUnion()) {
3275 if (FieldBaseElementType->isReferenceType()) {
3276 SemaRef.Diag(Constructor->getLocation(),
3277 diag::err_uninitialized_member_in_ctor)
3278 << (int)Constructor->isImplicit()
3279 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3280 << 0 << Field->getDeclName();
3281 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3282 return true;
3283 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003284
Alexis Hunt8b455182011-05-17 00:19:05 +00003285 if (FieldBaseElementType.isConstQualified()) {
3286 SemaRef.Diag(Constructor->getLocation(),
3287 diag::err_uninitialized_member_in_ctor)
3288 << (int)Constructor->isImplicit()
3289 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290 << 1 << Field->getDeclName();
3291 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292 return true;
3293 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003294 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003295
David Blaikiebbafb8a2012-03-11 07:00:24 +00003296 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003297 FieldBaseElementType->isObjCRetainableType() &&
3298 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3299 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003300 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003301 // Default-initialize Objective-C pointers to NULL.
3302 CXXMemberInit
3303 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3304 Loc, Loc,
3305 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3306 Loc);
3307 return false;
3308 }
3309
Anders Carlsson3c1db572010-04-23 02:15:47 +00003310 // Nothing to initialize.
3311 CXXMemberInit = 0;
3312 return false;
3313}
John McCallbc83b3f2010-05-20 23:23:51 +00003314
3315namespace {
3316struct BaseAndFieldInfo {
3317 Sema &S;
3318 CXXConstructorDecl *Ctor;
3319 bool AnyErrorsInInits;
3320 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003321 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003322 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003323
3324 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3325 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003326 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3327 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003328 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003329 else if (Generated && Ctor->isMoveConstructor())
3330 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003331 else if (Ctor->getInheritedConstructor())
3332 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003333 else
3334 IIK = IIK_Default;
3335 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003336
3337 bool isImplicitCopyOrMove() const {
3338 switch (IIK) {
3339 case IIK_Copy:
3340 case IIK_Move:
3341 return true;
3342
3343 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003344 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003345 return false;
3346 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003347
3348 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003349 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003350
3351 bool addFieldInitializer(CXXCtorInitializer *Init) {
3352 AllToInit.push_back(Init);
3353
3354 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003355 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003356 S.UnusedPrivateFields.remove(Init->getAnyMember());
3357
3358 return false;
3359 }
John McCallbc83b3f2010-05-20 23:23:51 +00003360};
3361}
3362
Richard Smithc94ec842011-09-19 13:34:43 +00003363/// \brief Determine whether the given indirect field declaration is somewhere
3364/// within an anonymous union.
3365static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3366 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3367 CEnd = F->chain_end();
3368 C != CEnd; ++C)
3369 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3370 if (Record->isUnion())
3371 return true;
3372
3373 return false;
3374}
3375
Douglas Gregor10f939c2011-11-02 23:04:16 +00003376/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3377/// array type.
3378static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3379 if (T->isIncompleteArrayType())
3380 return true;
3381
3382 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3383 if (!ArrayT->getSize())
3384 return true;
3385
3386 T = ArrayT->getElementType();
3387 }
3388
3389 return false;
3390}
3391
Richard Smith938f40b2011-06-11 17:19:42 +00003392static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003393 FieldDecl *Field,
3394 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003395 if (Field->isInvalidDecl())
3396 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003397
Chandler Carruth139e9622010-06-30 02:59:29 +00003398 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003399 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3400 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003401
Richard Smith0a8cfc72012-08-07 21:30:42 +00003402 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith938f40b2011-06-11 17:19:42 +00003403 // has a brace-or-equal-initializer, the entity is initialized as specified
3404 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00003405 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003406 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3407 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003408 CXXCtorInitializer *Init;
3409 if (Indirect)
3410 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3411 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003412 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003413 SourceLocation());
3414 else
3415 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3416 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003417 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003418 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003419 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003420 }
3421
Richard Smith12d5ed82011-09-18 11:14:50 +00003422 // Don't build an implicit initializer for union members if none was
3423 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00003424 if (Field->getParent()->isUnion() ||
3425 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00003426 return false;
3427
Douglas Gregor10f939c2011-11-02 23:04:16 +00003428 // Don't initialize incomplete or zero-length arrays.
3429 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3430 return false;
3431
John McCallbc83b3f2010-05-20 23:23:51 +00003432 // Don't try to build an implicit initializer if there were semantic
3433 // errors in any of the initializers (and therefore we might be
3434 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003435 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003436 return false;
3437
Alexis Hunt1d792652011-01-08 20:30:50 +00003438 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003439 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3440 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003441 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003442
Richard Smith0a8cfc72012-08-07 21:30:42 +00003443 if (!Init)
3444 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003445
Richard Smith0a8cfc72012-08-07 21:30:42 +00003446 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003447}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003448
3449bool
3450Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3451 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003452 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003453 Constructor->setNumCtorInitializers(1);
3454 CXXCtorInitializer **initializer =
3455 new (Context) CXXCtorInitializer*[1];
3456 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3457 Constructor->setCtorInitializers(initializer);
3458
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003459 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003460 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003461 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3462 }
3463
Alexis Hunte2622992011-05-05 00:05:47 +00003464 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003465
Alexis Hunt61bc1732011-05-01 07:04:31 +00003466 return false;
3467}
Douglas Gregor493627b2011-08-10 15:22:55 +00003468
David Blaikie3fc2f912013-01-17 05:26:25 +00003469bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3470 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003471 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003472 // Just store the initializers as written, they will be checked during
3473 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003474 if (!Initializers.empty()) {
3475 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003476 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003477 new (Context) CXXCtorInitializer*[Initializers.size()];
3478 memcpy(baseOrMemberInitializers, Initializers.data(),
3479 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003480 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003481 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003482
3483 // Let template instantiation know whether we had errors.
3484 if (AnyErrors)
3485 Constructor->setInvalidDecl();
3486
Anders Carlssondb0a9652010-04-02 06:26:44 +00003487 return false;
3488 }
3489
John McCallbc83b3f2010-05-20 23:23:51 +00003490 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003491
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003492 // We need to build the initializer AST according to order of construction
3493 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003494 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003495 if (!ClassDecl)
3496 return true;
3497
Eli Friedman9cf6b592009-11-09 19:20:36 +00003498 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003499
David Blaikie3fc2f912013-01-17 05:26:25 +00003500 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003501 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003502
Anders Carlssondb0a9652010-04-02 06:26:44 +00003503 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003504 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003505 else
Francois Pichetd583da02010-12-04 09:14:42 +00003506 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003507 }
3508
Anders Carlsson43c64af2010-04-21 19:52:01 +00003509 // Keep track of the direct virtual bases.
3510 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3511 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3512 E = ClassDecl->bases_end(); I != E; ++I) {
3513 if (I->isVirtual())
3514 DirectVBases.insert(I);
3515 }
3516
Anders Carlssondb0a9652010-04-02 06:26:44 +00003517 // Push virtual bases before others.
3518 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3519 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3520
Alexis Hunt1d792652011-01-08 20:30:50 +00003521 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003522 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003523 // [class.base.init]p7, per DR257:
3524 // A mem-initializer where the mem-initializer-id names a virtual base
3525 // class is ignored during execution of a constructor of any class that
3526 // is not the most derived class.
3527 if (ClassDecl->isAbstract()) {
3528 // FIXME: Provide a fixit to remove the base specifier. This requires
3529 // tracking the location of the associated comma for a base specifier.
3530 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3531 << VBase->getType() << ClassDecl;
3532 DiagnoseAbstractType(ClassDecl);
3533 }
3534
John McCallbc83b3f2010-05-20 23:23:51 +00003535 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003536 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3537 // [class.base.init]p8, per DR257:
3538 // If a given [...] base class is not named by a mem-initializer-id
3539 // [...] and the entity is not a virtual base class of an abstract
3540 // class, then [...] the entity is default-initialized.
Anders Carlsson43c64af2010-04-21 19:52:01 +00003541 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003542 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003543 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithbc46e432013-07-22 02:56:56 +00003544 VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003545 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003546 HadError = true;
3547 continue;
3548 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003549
John McCallbc83b3f2010-05-20 23:23:51 +00003550 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003551 }
3552 }
Mike Stump11289f42009-09-09 15:08:12 +00003553
John McCallbc83b3f2010-05-20 23:23:51 +00003554 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003555 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3556 E = ClassDecl->bases_end(); Base != E; ++Base) {
3557 // Virtuals are in the virtual base list and already constructed.
3558 if (Base->isVirtual())
3559 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003560
Alexis Hunt1d792652011-01-08 20:30:50 +00003561 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003562 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3563 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003564 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003565 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003566 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003567 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003568 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003569 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003570 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003571 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003572
John McCallbc83b3f2010-05-20 23:23:51 +00003573 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003574 }
3575 }
Mike Stump11289f42009-09-09 15:08:12 +00003576
John McCallbc83b3f2010-05-20 23:23:51 +00003577 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00003578 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3579 MemEnd = ClassDecl->decls_end();
3580 Mem != MemEnd; ++Mem) {
3581 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003582 // C++ [class.bit]p2:
3583 // A declaration for a bit-field that omits the identifier declares an
3584 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3585 // initialized.
3586 if (F->isUnnamedBitfield())
3587 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003588
Sebastian Redl22653ba2011-08-30 19:58:05 +00003589 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003590 // handle anonymous struct/union fields based on their individual
3591 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003592 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003593 continue;
3594
3595 if (CollectFieldInitializer(*this, Info, F))
3596 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003597 continue;
3598 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003599
3600 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003601 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003602 continue;
3603
3604 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3605 if (F->getType()->isIncompleteArrayType()) {
3606 assert(ClassDecl->hasFlexibleArrayMember() &&
3607 "Incomplete array type is not valid");
3608 continue;
3609 }
3610
Douglas Gregor493627b2011-08-10 15:22:55 +00003611 // Initialize each field of an anonymous struct individually.
3612 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3613 HadError = true;
3614
3615 continue;
3616 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
David Blaikie3fc2f912013-01-17 05:26:25 +00003619 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003620 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003621 Constructor->setNumCtorInitializers(NumInitializers);
3622 CXXCtorInitializer **baseOrMemberInitializers =
3623 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003624 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003625 NumInitializers * sizeof(CXXCtorInitializer*));
3626 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003627
John McCalla6309952010-03-16 21:39:52 +00003628 // Constructors implicitly reference the base and member
3629 // destructors.
3630 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3631 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003632 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003633
3634 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003635}
3636
David Blaikieb61b8152013-01-17 08:49:22 +00003637static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003638 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003639 const RecordDecl *RD = RT->getDecl();
3640 if (RD->isAnonymousStructOrUnion()) {
3641 for (RecordDecl::field_iterator Field = RD->field_begin(),
3642 E = RD->field_end(); Field != E; ++Field)
3643 PopulateKeysForFields(*Field, IdealInits);
3644 return;
3645 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003646 }
David Blaikieb61b8152013-01-17 08:49:22 +00003647 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003648}
3649
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003650static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3651 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003652}
3653
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003654static const void *GetKeyForMember(ASTContext &Context,
3655 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003656 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003657 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003658
David Blaikieb61b8152013-01-17 08:49:22 +00003659 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003660}
3661
David Blaikie3fc2f912013-01-17 05:26:25 +00003662static void DiagnoseBaseOrMemInitializerOrder(
3663 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3664 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003665 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003666 return;
Mike Stump11289f42009-09-09 15:08:12 +00003667
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003668 // Don't check initializers order unless the warning is enabled at the
3669 // location of at least one initializer.
3670 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003671 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003672 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003673 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3674 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003675 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003676 ShouldCheckOrder = true;
3677 break;
3678 }
3679 }
3680 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003681 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003682
John McCallbb7b6582010-04-10 07:37:23 +00003683 // Build the list of bases and members in the order that they'll
3684 // actually be initialized. The explicit initializers should be in
3685 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003686 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003687
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003688 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3689
John McCallbb7b6582010-04-10 07:37:23 +00003690 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003691 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003692 ClassDecl->vbases_begin(),
3693 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003694 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003695
John McCallbb7b6582010-04-10 07:37:23 +00003696 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003697 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003698 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003699 if (Base->isVirtual())
3700 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003701 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003702 }
Mike Stump11289f42009-09-09 15:08:12 +00003703
John McCallbb7b6582010-04-10 07:37:23 +00003704 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003705 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003706 E = ClassDecl->field_end(); Field != E; ++Field) {
3707 if (Field->isUnnamedBitfield())
3708 continue;
3709
David Blaikieb61b8152013-01-17 08:49:22 +00003710 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003711 }
3712
John McCallbb7b6582010-04-10 07:37:23 +00003713 unsigned NumIdealInits = IdealInitKeys.size();
3714 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003715
Alexis Hunt1d792652011-01-08 20:30:50 +00003716 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003717 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003718 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003719 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003720
3721 // Scan forward to try to find this initializer in the idealized
3722 // initializers list.
3723 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3724 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003725 break;
John McCallbb7b6582010-04-10 07:37:23 +00003726
3727 // If we didn't find this initializer, it must be because we
3728 // scanned past it on a previous iteration. That can only
3729 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003730 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003731 Sema::SemaDiagnosticBuilder D =
3732 SemaRef.Diag(PrevInit->getSourceLocation(),
3733 diag::warn_initializer_out_of_order);
3734
Francois Pichetd583da02010-12-04 09:14:42 +00003735 if (PrevInit->isAnyMemberInitializer())
3736 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003737 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003738 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003739
Francois Pichetd583da02010-12-04 09:14:42 +00003740 if (Init->isAnyMemberInitializer())
3741 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003742 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003743 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003744
3745 // Move back to the initializer's location in the ideal list.
3746 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3747 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003748 break;
John McCallbb7b6582010-04-10 07:37:23 +00003749
3750 assert(IdealIndex != NumIdealInits &&
3751 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003752 }
John McCallbb7b6582010-04-10 07:37:23 +00003753
3754 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003755 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003756}
3757
John McCall23eebd92010-04-10 09:28:51 +00003758namespace {
3759bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003760 CXXCtorInitializer *Init,
3761 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003762 if (!PrevInit) {
3763 PrevInit = Init;
3764 return false;
3765 }
3766
Douglas Gregorea306a12013-03-25 23:28:23 +00003767 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003768 S.Diag(Init->getSourceLocation(),
3769 diag::err_multiple_mem_initialization)
3770 << Field->getDeclName()
3771 << Init->getSourceRange();
3772 else {
John McCall424cec92011-01-19 06:33:43 +00003773 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003774 assert(BaseClass && "neither field nor base");
3775 S.Diag(Init->getSourceLocation(),
3776 diag::err_multiple_base_initialization)
3777 << QualType(BaseClass, 0)
3778 << Init->getSourceRange();
3779 }
3780 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3781 << 0 << PrevInit->getSourceRange();
3782
3783 return true;
3784}
3785
Alexis Hunt1d792652011-01-08 20:30:50 +00003786typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003787typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3788
3789bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003790 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003791 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003792 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003793 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003794 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003795
3796 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003797 if (Parent->isUnion()) {
3798 UnionEntry &En = Unions[Parent];
3799 if (En.first && En.first != Child) {
3800 S.Diag(Init->getSourceLocation(),
3801 diag::err_multiple_mem_union_initialization)
3802 << Field->getDeclName()
3803 << Init->getSourceRange();
3804 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3805 << 0 << En.second->getSourceRange();
3806 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003807 }
3808 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003809 En.first = Child;
3810 En.second = Init;
3811 }
David Blaikie0f65d592011-11-17 06:01:57 +00003812 if (!Parent->isAnonymousStructOrUnion())
3813 return false;
John McCall23eebd92010-04-10 09:28:51 +00003814 }
3815
3816 Child = Parent;
3817 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003818 }
John McCall23eebd92010-04-10 09:28:51 +00003819
3820 return false;
3821}
3822}
3823
Anders Carlssone857b292010-04-02 03:37:03 +00003824/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003825void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003826 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003827 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003828 bool AnyErrors) {
3829 if (!ConstructorDecl)
3830 return;
3831
3832 AdjustDeclIfTemplate(ConstructorDecl);
3833
3834 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003835 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003836
3837 if (!Constructor) {
3838 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3839 return;
3840 }
3841
John McCall23eebd92010-04-10 09:28:51 +00003842 // Mapping for the duplicate initializers check.
3843 // For member initializers, this is keyed with a FieldDecl*.
3844 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003845 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003846
3847 // Mapping for the inconsistent anonymous-union initializers check.
3848 RedundantUnionMap MemberUnions;
3849
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003850 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003851 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003852 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003853
Abramo Bagnara341d7832010-05-26 18:09:23 +00003854 // Set the source order index.
3855 Init->setSourceOrder(i);
3856
Francois Pichetd583da02010-12-04 09:14:42 +00003857 if (Init->isAnyMemberInitializer()) {
3858 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003859 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3860 CheckRedundantUnionInit(*this, Init, MemberUnions))
3861 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003862 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003863 const void *Key =
3864 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003865 if (CheckRedundantInit(*this, Init, Members[Key]))
3866 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003867 } else {
3868 assert(Init->isDelegatingInitializer());
3869 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003870 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003871 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003872 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003873 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003874 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003875 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003876 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003877 // Return immediately as the initializer is set.
3878 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003879 }
Anders Carlssone857b292010-04-02 03:37:03 +00003880 }
3881
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003882 if (HadError)
3883 return;
3884
David Blaikie3fc2f912013-01-17 05:26:25 +00003885 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003886
David Blaikie3fc2f912013-01-17 05:26:25 +00003887 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003888
Richard Trieuef64e942013-10-25 00:56:00 +00003889 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003890}
3891
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003892void
John McCalla6309952010-03-16 21:39:52 +00003893Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3894 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003895 // Ignore dependent contexts. Also ignore unions, since their members never
3896 // have destructors implicitly called.
3897 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003898 return;
John McCall1064d7e2010-03-16 05:22:47 +00003899
3900 // FIXME: all the access-control diagnostics are positioned on the
3901 // field/base declaration. That's probably good; that said, the
3902 // user might reasonably want to know why the destructor is being
3903 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003904
Anders Carlssondee9a302009-11-17 04:44:12 +00003905 // Non-static data members.
3906 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3907 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003908 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003909 if (Field->isInvalidDecl())
3910 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003911
3912 // Don't destroy incomplete or zero-length arrays.
3913 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3914 continue;
3915
Anders Carlssondee9a302009-11-17 04:44:12 +00003916 QualType FieldType = Context.getBaseElementType(Field->getType());
3917
3918 const RecordType* RT = FieldType->getAs<RecordType>();
3919 if (!RT)
3920 continue;
3921
3922 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003923 if (FieldClassDecl->isInvalidDecl())
3924 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003925 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003926 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003927 // The destructor for an implicit anonymous union member is never invoked.
3928 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3929 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003930
Douglas Gregore71edda2010-07-01 22:47:18 +00003931 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003932 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003933 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003934 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003935 << Field->getDeclName()
3936 << FieldType);
3937
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003938 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003939 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003940 }
3941
John McCall1064d7e2010-03-16 05:22:47 +00003942 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3943
Anders Carlssondee9a302009-11-17 04:44:12 +00003944 // Bases.
3945 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3946 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003947 // Bases are always records in a well-formed non-dependent class.
3948 const RecordType *RT = Base->getType()->getAs<RecordType>();
3949
3950 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003951 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003952 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003953
John McCall1064d7e2010-03-16 05:22:47 +00003954 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003955 // If our base class is invalid, we probably can't get its dtor anyway.
3956 if (BaseClassDecl->isInvalidDecl())
3957 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003958 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003959 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003960
Douglas Gregore71edda2010-07-01 22:47:18 +00003961 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003962 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003963
3964 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003965 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003966 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003967 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00003968 << Base->getSourceRange(),
3969 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00003970
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003971 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003972 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003973 }
3974
3975 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003976 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3977 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003978
3979 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00003980 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003981
3982 // Ignore direct virtual bases.
3983 if (DirectVirtualBases.count(RT))
3984 continue;
3985
John McCall1064d7e2010-03-16 05:22:47 +00003986 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003987 // If our base class is invalid, we probably can't get its dtor anyway.
3988 if (BaseClassDecl->isInvalidDecl())
3989 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003990 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003991 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003992
Douglas Gregore71edda2010-07-01 22:47:18 +00003993 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003994 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00003995 if (CheckDestructorAccess(
3996 ClassDecl->getLocation(), Dtor,
3997 PDiag(diag::err_access_dtor_vbase)
3998 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3999 Context.getTypeDeclType(ClassDecl)) ==
4000 AR_accessible) {
4001 CheckDerivedToBaseConversion(
4002 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4003 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4004 SourceRange(), DeclarationName(), 0);
4005 }
John McCall1064d7e2010-03-16 05:22:47 +00004006
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004007 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004008 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004009 }
4010}
4011
John McCall48871652010-08-21 09:40:31 +00004012void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004013 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004014 return;
Mike Stump11289f42009-09-09 15:08:12 +00004015
Mike Stump11289f42009-09-09 15:08:12 +00004016 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004017 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004018 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004019 DiagnoseUninitializedFields(*this, Constructor);
4020 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004021}
4022
Mike Stump11289f42009-09-09 15:08:12 +00004023bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004024 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004025 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4026 unsigned DiagID;
4027 AbstractDiagSelID SelID;
4028
4029 public:
4030 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4031 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004032
4033 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004034 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004035 if (SelID == -1)
4036 S.Diag(Loc, DiagID) << T;
4037 else
4038 S.Diag(Loc, DiagID) << SelID << T;
4039 }
4040 } Diagnoser(DiagID, SelID);
4041
4042 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004043}
4044
Anders Carlssoneabf7702009-08-27 00:13:57 +00004045bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004046 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004047 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004048 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004049
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004050 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004051 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004052
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004053 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004054 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004055 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004056 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004057
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004058 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004059 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004060 }
Mike Stump11289f42009-09-09 15:08:12 +00004061
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004062 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004063 if (!RT)
4064 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCall67da35c2010-02-04 22:26:26 +00004066 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004067
John McCall02db245d2010-08-18 09:41:07 +00004068 // We can't answer whether something is abstract until it has a
4069 // definition. If it's currently being defined, we'll walk back
4070 // over all the declarations when we have a full definition.
4071 const CXXRecordDecl *Def = RD->getDefinition();
4072 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004073 return false;
4074
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004075 if (!RD->isAbstract())
4076 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004077
Douglas Gregorae298422012-05-04 17:09:59 +00004078 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004079 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004080
John McCall02db245d2010-08-18 09:41:07 +00004081 return true;
4082}
4083
4084void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4085 // Check if we've already emitted the list of pure virtual functions
4086 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004087 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004088 return;
Mike Stump11289f42009-09-09 15:08:12 +00004089
Richard Smithbc46e432013-07-22 02:56:56 +00004090 // If the diagnostic is suppressed, don't emit the notes. We're only
4091 // going to emit them once, so try to attach them to a diagnostic we're
4092 // actually going to show.
4093 if (Diags.isLastDiagnosticIgnored())
4094 return;
4095
Douglas Gregor4165bd62010-03-23 23:47:56 +00004096 CXXFinalOverriderMap FinalOverriders;
4097 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004098
Anders Carlssona2f74f32010-06-03 01:00:02 +00004099 // Keep a set of seen pure methods so we won't diagnose the same method
4100 // more than once.
4101 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4102
Douglas Gregor4165bd62010-03-23 23:47:56 +00004103 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4104 MEnd = FinalOverriders.end();
4105 M != MEnd;
4106 ++M) {
4107 for (OverridingMethods::iterator SO = M->second.begin(),
4108 SOEnd = M->second.end();
4109 SO != SOEnd; ++SO) {
4110 // C++ [class.abstract]p4:
4111 // A class is abstract if it contains or inherits at least one
4112 // pure virtual function for which the final overrider is pure
4113 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004114
Douglas Gregor4165bd62010-03-23 23:47:56 +00004115 //
4116 if (SO->second.size() != 1)
4117 continue;
4118
4119 if (!SO->second.front().Method->isPure())
4120 continue;
4121
Anders Carlssona2f74f32010-06-03 01:00:02 +00004122 if (!SeenPureMethods.insert(SO->second.front().Method))
4123 continue;
4124
Douglas Gregor4165bd62010-03-23 23:47:56 +00004125 Diag(SO->second.front().Method->getLocation(),
4126 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004127 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004128 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004129 }
4130
4131 if (!PureVirtualClassDiagSet)
4132 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4133 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004134}
4135
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004136namespace {
John McCall02db245d2010-08-18 09:41:07 +00004137struct AbstractUsageInfo {
4138 Sema &S;
4139 CXXRecordDecl *Record;
4140 CanQualType AbstractType;
4141 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004142
John McCall02db245d2010-08-18 09:41:07 +00004143 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4144 : S(S), Record(Record),
4145 AbstractType(S.Context.getCanonicalType(
4146 S.Context.getTypeDeclType(Record))),
4147 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004148
John McCall02db245d2010-08-18 09:41:07 +00004149 void DiagnoseAbstractType() {
4150 if (Invalid) return;
4151 S.DiagnoseAbstractType(Record);
4152 Invalid = true;
4153 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004154
John McCall02db245d2010-08-18 09:41:07 +00004155 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4156};
4157
4158struct CheckAbstractUsage {
4159 AbstractUsageInfo &Info;
4160 const NamedDecl *Ctx;
4161
4162 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4163 : Info(Info), Ctx(Ctx) {}
4164
4165 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4166 switch (TL.getTypeLocClass()) {
4167#define ABSTRACT_TYPELOC(CLASS, PARENT)
4168#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004169 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004170#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004171 }
John McCall02db245d2010-08-18 09:41:07 +00004172 }
Mike Stump11289f42009-09-09 15:08:12 +00004173
John McCall02db245d2010-08-18 09:41:07 +00004174 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4175 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4176 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004177 if (!TL.getArg(I))
4178 continue;
4179
John McCall02db245d2010-08-18 09:41:07 +00004180 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4181 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004182 }
John McCall02db245d2010-08-18 09:41:07 +00004183 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004184
John McCall02db245d2010-08-18 09:41:07 +00004185 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4186 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4187 }
Mike Stump11289f42009-09-09 15:08:12 +00004188
John McCall02db245d2010-08-18 09:41:07 +00004189 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4190 // Visit the type parameters from a permissive context.
4191 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4192 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4193 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4194 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4195 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4196 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004197 }
John McCall02db245d2010-08-18 09:41:07 +00004198 }
Mike Stump11289f42009-09-09 15:08:12 +00004199
John McCall02db245d2010-08-18 09:41:07 +00004200 // Visit pointee types from a permissive context.
4201#define CheckPolymorphic(Type) \
4202 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4203 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4204 }
4205 CheckPolymorphic(PointerTypeLoc)
4206 CheckPolymorphic(ReferenceTypeLoc)
4207 CheckPolymorphic(MemberPointerTypeLoc)
4208 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004209 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004210
John McCall02db245d2010-08-18 09:41:07 +00004211 /// Handle all the types we haven't given a more specific
4212 /// implementation for above.
4213 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214 // Every other kind of type that we haven't called out already
4215 // that has an inner type is either (1) sugar or (2) contains that
4216 // inner type in some way as a subobject.
4217 if (TypeLoc Next = TL.getNextTypeLoc())
4218 return Visit(Next, Sel);
4219
4220 // If there's no inner type and we're in a permissive context,
4221 // don't diagnose.
4222 if (Sel == Sema::AbstractNone) return;
4223
4224 // Check whether the type matches the abstract type.
4225 QualType T = TL.getType();
4226 if (T->isArrayType()) {
4227 Sel = Sema::AbstractArrayType;
4228 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004229 }
John McCall02db245d2010-08-18 09:41:07 +00004230 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4231 if (CT != Info.AbstractType) return;
4232
4233 // It matched; do some magic.
4234 if (Sel == Sema::AbstractArrayType) {
4235 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4236 << T << TL.getSourceRange();
4237 } else {
4238 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4239 << Sel << T << TL.getSourceRange();
4240 }
4241 Info.DiagnoseAbstractType();
4242 }
4243};
4244
4245void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4246 Sema::AbstractDiagSelID Sel) {
4247 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4248}
4249
4250}
4251
4252/// Check for invalid uses of an abstract type in a method declaration.
4253static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4254 CXXMethodDecl *MD) {
4255 // No need to do the check on definitions, which require that
4256 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004257 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004258 return;
4259
4260 // For safety's sake, just ignore it if we don't have type source
4261 // information. This should never happen for non-implicit methods,
4262 // but...
4263 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4264 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4265}
4266
4267/// Check for invalid uses of an abstract type within a class definition.
4268static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4269 CXXRecordDecl *RD) {
4270 for (CXXRecordDecl::decl_iterator
4271 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4272 Decl *D = *I;
4273 if (D->isImplicit()) continue;
4274
4275 // Methods and method templates.
4276 if (isa<CXXMethodDecl>(D)) {
4277 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4278 } else if (isa<FunctionTemplateDecl>(D)) {
4279 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4280 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4281
4282 // Fields and static variables.
4283 } else if (isa<FieldDecl>(D)) {
4284 FieldDecl *FD = cast<FieldDecl>(D);
4285 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4286 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4287 } else if (isa<VarDecl>(D)) {
4288 VarDecl *VD = cast<VarDecl>(D);
4289 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4290 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4291
4292 // Nested classes and class templates.
4293 } else if (isa<CXXRecordDecl>(D)) {
4294 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4295 } else if (isa<ClassTemplateDecl>(D)) {
4296 CheckAbstractClassUsage(Info,
4297 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4298 }
4299 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004300}
4301
Douglas Gregorc99f1552009-12-03 18:33:45 +00004302/// \brief Perform semantic checks on a class definition that has been
4303/// completing, introducing implicitly-declared members, checking for
4304/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004305void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004306 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004307 return;
4308
John McCall02db245d2010-08-18 09:41:07 +00004309 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4310 AbstractUsageInfo Info(*this, Record);
4311 CheckAbstractClassUsage(Info, Record);
4312 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004313
4314 // If this is not an aggregate type and has no user-declared constructor,
4315 // complain about any non-static data members of reference or const scalar
4316 // type, since they will never get initializers.
4317 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004318 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4319 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004320 bool Complained = false;
4321 for (RecordDecl::field_iterator F = Record->field_begin(),
4322 FEnd = Record->field_end();
4323 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004324 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004325 continue;
4326
Douglas Gregor454a5b62010-04-15 00:00:53 +00004327 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004328 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004329 if (!Complained) {
4330 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4331 << Record->getTagKind() << Record;
4332 Complained = true;
4333 }
4334
4335 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4336 << F->getType()->isReferenceType()
4337 << F->getDeclName();
4338 }
4339 }
4340 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004341
Anders Carlssone771e762011-01-25 18:08:22 +00004342 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004343 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004344
4345 if (Record->getIdentifier()) {
4346 // C++ [class.mem]p13:
4347 // If T is the name of a class, then each of the following shall have a
4348 // name different from T:
4349 // - every member of every anonymous union that is a member of class T.
4350 //
4351 // C++ [class.mem]p14:
4352 // In addition, if class T has a user-declared constructor (12.1), every
4353 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004354 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4355 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4356 ++I) {
4357 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004358 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4359 isa<IndirectFieldDecl>(D)) {
4360 Diag(D->getLocation(), diag::err_member_name_of_class)
4361 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004362 break;
4363 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004364 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004365 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004366
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004367 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004368 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004369 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004370 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004371 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4372 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4373 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004374
David Majnemera5433082013-10-18 00:33:31 +00004375 if (Record->isAbstract()) {
4376 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4377 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4378 << FA->isSpelledAsSealed();
4379 DiagnoseAbstractType(Record);
4380 }
David Blaikie348df502012-09-21 03:21:07 +00004381 }
4382
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004383 if (!Record->isDependentType()) {
4384 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4385 MEnd = Record->method_end();
4386 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004387 // See if a method overloads virtual methods in a base
4388 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004389 if (!M->isStatic())
Eli Friedmanaf65120b2013-09-05 23:51:03 +00004390 DiagnoseHiddenVirtualMethods(*M);
Richard Smithbd305122012-12-11 01:14:52 +00004391
4392 // Check whether the explicitly-defaulted special members are valid.
4393 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4394 CheckExplicitlyDefaultedSpecialMember(*M);
4395
4396 // For an explicitly defaulted or deleted special member, we defer
4397 // determining triviality until the class is complete. That time is now!
4398 if (!M->isImplicit() && !M->isUserProvided()) {
4399 CXXSpecialMember CSM = getSpecialMember(*M);
4400 if (CSM != CXXInvalid) {
4401 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4402
4403 // Inform the class that we've finished declaring this member.
4404 Record->finishedDefaultedOrDeletedMember(*M);
4405 }
4406 }
4407 }
4408 }
4409
4410 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4411 // function that is not a constructor declares that member function to be
4412 // const. [...] The class of which that function is a member shall be
4413 // a literal type.
4414 //
4415 // If the class has virtual bases, any constexpr members will already have
4416 // been diagnosed by the checks performed on the member declaration, so
4417 // suppress this (less useful) diagnostic.
4418 //
4419 // We delay this until we know whether an explicitly-defaulted (or deleted)
4420 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004421 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004422 !Record->isLiteral() && !Record->getNumVBases()) {
4423 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4424 MEnd = Record->method_end();
4425 M != MEnd; ++M) {
4426 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4427 switch (Record->getTemplateSpecializationKind()) {
4428 case TSK_ImplicitInstantiation:
4429 case TSK_ExplicitInstantiationDeclaration:
4430 case TSK_ExplicitInstantiationDefinition:
4431 // If a template instantiates to a non-literal type, but its members
4432 // instantiate to constexpr functions, the template is technically
4433 // ill-formed, but we allow it for sanity.
4434 continue;
4435
4436 case TSK_Undeclared:
4437 case TSK_ExplicitSpecialization:
4438 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4439 diag::err_constexpr_method_non_literal);
4440 break;
4441 }
4442
4443 // Only produce one error per class.
4444 break;
4445 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004446 }
4447 }
Sebastian Redl08905022011-02-05 19:23:19 +00004448
Warren Hunt8f8bad72013-10-11 20:19:00 +00004449 // Check to see if we're trying to lay out a struct using the ms_struct
4450 // attribute that is dynamic.
4451 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4452 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4453 Record->dropAttr<MsStructAttr>();
4454 }
4455
Richard Smithc2bc61b2013-03-18 21:12:30 +00004456 // Declare inheriting constructors. We do this eagerly here because:
4457 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004458 // constructors from different classes.
4459 // - The lazy declaration of the other implicit constructors is so as to not
4460 // waste space and performance on classes that are not meant to be
4461 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004462 // have inheriting constructors.
4463 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004464}
4465
Richard Smith41c35d62013-11-27 03:39:20 +00004466/// Look up the special member function that would be called by a special
4467/// member function for a subobject of class type.
4468///
4469/// \param Class The class type of the subobject.
4470/// \param CSM The kind of special member function.
4471/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4472/// \param ConstRHS True if this is a copy operation with a const object
4473/// on its RHS, that is, if the argument to the outer special member
4474/// function is 'const' and this is not a field marked 'mutable'.
4475static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4476 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4477 unsigned FieldQuals, bool ConstRHS) {
4478 unsigned LHSQuals = 0;
4479 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4480 LHSQuals = FieldQuals;
4481
4482 unsigned RHSQuals = FieldQuals;
4483 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4484 RHSQuals = 0;
4485 else if (ConstRHS)
4486 RHSQuals |= Qualifiers::Const;
4487
4488 return S.LookupSpecialMember(Class, CSM,
4489 RHSQuals & Qualifiers::Const,
4490 RHSQuals & Qualifiers::Volatile,
4491 false,
4492 LHSQuals & Qualifiers::Const,
4493 LHSQuals & Qualifiers::Volatile);
4494}
4495
Richard Smithb5800092012-06-10 05:43:50 +00004496/// Is the special member function which would be selected to perform the
4497/// specified operation on the specified class type a constexpr constructor?
4498static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4499 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004500 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004501 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004502 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004503 if (!SMOR || !SMOR->getMethod())
4504 // A constructor we wouldn't select can't be "involved in initializing"
4505 // anything.
4506 return true;
4507 return SMOR->getMethod()->isConstexpr();
4508}
4509
4510/// Determine whether the specified special member function would be constexpr
4511/// if it were implicitly defined.
4512static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4513 Sema::CXXSpecialMember CSM,
4514 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004515 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004516 return false;
4517
4518 // C++11 [dcl.constexpr]p4:
4519 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004520 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004521 switch (CSM) {
4522 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004523 // Since default constructor lookup is essentially trivial (and cannot
4524 // involve, for instance, template instantiation), we compute whether a
4525 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4526 //
4527 // This is important for performance; we need to know whether the default
4528 // constructor is constexpr to determine whether the type is a literal type.
4529 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4530
Richard Smithb5800092012-06-10 05:43:50 +00004531 case Sema::CXXCopyConstructor:
4532 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004533 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004534 break;
4535
4536 case Sema::CXXCopyAssignment:
4537 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004538 if (!S.getLangOpts().CPlusPlus1y)
4539 return false;
4540 // In C++1y, we need to perform overload resolution.
4541 Ctor = false;
4542 break;
4543
Richard Smithb5800092012-06-10 05:43:50 +00004544 case Sema::CXXDestructor:
4545 case Sema::CXXInvalid:
4546 return false;
4547 }
4548
4549 // -- if the class is a non-empty union, or for each non-empty anonymous
4550 // union member of a non-union class, exactly one non-static data member
4551 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004552 //
4553 // If we squint, this is guaranteed, since exactly one non-static data member
4554 // will be initialized (if the constructor isn't deleted), we just don't know
4555 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004556 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004557 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004558
4559 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004560 if (Ctor && ClassDecl->getNumVBases())
4561 return false;
4562
4563 // C++1y [class.copy]p26:
4564 // -- [the class] is a literal type, and
4565 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004566 return false;
4567
4568 // -- every constructor involved in initializing [...] base class
4569 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004570 // -- the assignment operator selected to copy/move each direct base
4571 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004572 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4573 BEnd = ClassDecl->bases_end();
4574 B != BEnd; ++B) {
4575 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4576 if (!BaseType) continue;
4577
4578 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004579 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004580 return false;
4581 }
4582
4583 // -- every constructor involved in initializing non-static data members
4584 // [...] shall be a constexpr constructor;
4585 // -- every non-static data member and base class sub-object shall be
4586 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004587 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004588 // thereof), the assignment operator selected to copy/move that member is
4589 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004590 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4591 FEnd = ClassDecl->field_end();
4592 F != FEnd; ++F) {
4593 if (F->isInvalidDecl())
4594 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004595 QualType BaseType = S.Context.getBaseElementType(F->getType());
4596 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004597 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004598 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4599 BaseType.getCVRQualifiers(),
4600 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004601 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004602 }
4603 }
4604
4605 // All OK, it's constexpr!
4606 return true;
4607}
4608
Richard Smithd3b5c9082012-07-27 04:22:15 +00004609static Sema::ImplicitExceptionSpecification
4610computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4611 switch (S.getSpecialMember(MD)) {
4612 case Sema::CXXDefaultConstructor:
4613 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4614 case Sema::CXXCopyConstructor:
4615 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4616 case Sema::CXXCopyAssignment:
4617 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4618 case Sema::CXXMoveConstructor:
4619 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4620 case Sema::CXXMoveAssignment:
4621 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4622 case Sema::CXXDestructor:
4623 return S.ComputeDefaultedDtorExceptionSpec(MD);
4624 case Sema::CXXInvalid:
4625 break;
4626 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004627 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4628 "only special members have implicit exception specs");
4629 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004630}
4631
Richard Smith7f782272012-07-30 23:48:14 +00004632static void
4633updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4634 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4635 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4636 ExceptSpec.getEPI(EPI);
Richard Smith185be182013-04-10 05:48:59 +00004637 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4638 FPT->getArgTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004639}
4640
Reid Kleckner78af0702013-08-27 23:08:25 +00004641static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4642 CXXMethodDecl *MD) {
4643 FunctionProtoType::ExtProtoInfo EPI;
4644
4645 // Build an exception specification pointing back at this member.
4646 EPI.ExceptionSpecType = EST_Unevaluated;
4647 EPI.ExceptionSpecDecl = MD;
4648
4649 // Set the calling convention to the default for C++ instance methods.
4650 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4651 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4652 /*IsCXXMethod=*/true));
4653 return EPI;
4654}
4655
Richard Smithd3b5c9082012-07-27 04:22:15 +00004656void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4657 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4658 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4659 return;
4660
Richard Smith7f782272012-07-30 23:48:14 +00004661 // Evaluate the exception specification.
4662 ImplicitExceptionSpecification ExceptSpec =
4663 computeImplicitExceptionSpec(*this, Loc, MD);
4664
4665 // Update the type of the special member to use it.
4666 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4667
4668 // A user-provided destructor can be defined outside the class. When that
4669 // happens, be sure to update the exception specification on both
4670 // declarations.
4671 const FunctionProtoType *CanonicalFPT =
4672 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4673 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4674 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4675 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004676}
4677
Richard Smithb9e90b12012-05-15 04:39:51 +00004678void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4679 CXXRecordDecl *RD = MD->getParent();
4680 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004681
Richard Smithb9e90b12012-05-15 04:39:51 +00004682 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4683 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004684
4685 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004686 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004687 bool First = MD == MD->getCanonicalDecl();
4688
4689 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004690
4691 // C++11 [dcl.fct.def.default]p1:
4692 // A function that is explicitly defaulted shall
4693 // -- be a special member function (checked elsewhere),
4694 // -- have the same type (except for ref-qualifiers, and except that a
4695 // copy operation can take a non-const reference) as an implicit
4696 // declaration, and
4697 // -- not have default arguments.
4698 unsigned ExpectedParams = 1;
4699 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4700 ExpectedParams = 0;
4701 if (MD->getNumParams() != ExpectedParams) {
4702 // This also checks for default arguments: a copy or move constructor with a
4703 // default argument is classified as a default constructor, and assignment
4704 // operations and destructors can't have default arguments.
4705 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4706 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004707 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004708 } else if (MD->isVariadic()) {
4709 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4710 << CSM << MD->getSourceRange();
4711 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004712 }
4713
Richard Smithb9e90b12012-05-15 04:39:51 +00004714 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004715
Richard Smithb5800092012-06-10 05:43:50 +00004716 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004717 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004718 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004719 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004720 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004721
Richard Smithb9e90b12012-05-15 04:39:51 +00004722 QualType ReturnType = Context.VoidTy;
4723 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4724 // Check for return type matching.
4725 ReturnType = Type->getResultType();
4726 QualType ExpectedReturnType =
4727 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4728 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4729 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4730 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4731 HadError = true;
4732 }
4733
4734 // A defaulted special member cannot have cv-qualifiers.
4735 if (Type->getTypeQuals()) {
4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004737 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004738 HadError = true;
4739 }
4740 }
4741
4742 // Check for parameter type matching.
4743 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004744 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004745 if (ExpectedParams && ArgType->isReferenceType()) {
4746 // Argument must be reference to possibly-const T.
4747 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004748 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004749
4750 if (ReferentType.isVolatileQualified()) {
4751 Diag(MD->getLocation(),
4752 diag::err_defaulted_special_member_volatile_param) << CSM;
4753 HadError = true;
4754 }
4755
Richard Smithb5800092012-06-10 05:43:50 +00004756 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004757 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4758 Diag(MD->getLocation(),
4759 diag::err_defaulted_special_member_copy_const_param)
4760 << (CSM == CXXCopyAssignment);
4761 // FIXME: Explain why this special member can't be const.
4762 } else {
4763 Diag(MD->getLocation(),
4764 diag::err_defaulted_special_member_move_const_param)
4765 << (CSM == CXXMoveAssignment);
4766 }
4767 HadError = true;
4768 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004769 } else if (ExpectedParams) {
4770 // A copy assignment operator can take its argument by value, but a
4771 // defaulted one cannot.
4772 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004773 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004774 HadError = true;
4775 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004776
Richard Smithcc36f692011-12-22 02:22:31 +00004777 // C++11 [dcl.fct.def.default]p2:
4778 // An explicitly-defaulted function may be declared constexpr only if it
4779 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004780 // Do not apply this rule to members of class templates, since core issue 1358
4781 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004782 // functions which cannot be constexpr (for non-constructors in C++11 and for
4783 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004784 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4785 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004786 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4787 : isa<CXXConstructorDecl>(MD)) &&
4788 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004789 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4790 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004791 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004792 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004793 }
Richard Smithbd305122012-12-11 01:14:52 +00004794
Richard Smithcc36f692011-12-22 02:22:31 +00004795 // and may have an explicit exception-specification only if it is compatible
4796 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004797 if (Type->hasExceptionSpec()) {
4798 // Delay the check if this is the first declaration of the special member,
4799 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004800 if (First) {
4801 // If the exception specification needs to be instantiated, do so now,
4802 // before we clobber it with an EST_Unevaluated specification below.
4803 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4804 InstantiateExceptionSpec(MD->getLocStart(), MD);
4805 Type = MD->getType()->getAs<FunctionProtoType>();
4806 }
Richard Smithbd305122012-12-11 01:14:52 +00004807 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004808 } else
Richard Smithbd305122012-12-11 01:14:52 +00004809 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4810 }
Richard Smithcc36f692011-12-22 02:22:31 +00004811
4812 // If a function is explicitly defaulted on its first declaration,
4813 if (First) {
4814 // -- it is implicitly considered to be constexpr if the implicit
4815 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004816 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004817
Richard Smithb9e90b12012-05-15 04:39:51 +00004818 // -- it is implicitly considered to have the same exception-specification
4819 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004820 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4821 EPI.ExceptionSpecType = EST_Unevaluated;
4822 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004823 MD->setType(Context.getFunctionType(ReturnType,
4824 ArrayRef<QualType>(&ArgType,
4825 ExpectedParams),
4826 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004827 }
4828
Richard Smithb9e90b12012-05-15 04:39:51 +00004829 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004830 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004831 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004832 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004833 // C++11 [dcl.fct.def.default]p4:
4834 // [For a] user-provided explicitly-defaulted function [...] if such a
4835 // function is implicitly defined as deleted, the program is ill-formed.
4836 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4837 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004838 }
4839 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004840
Richard Smithb9e90b12012-05-15 04:39:51 +00004841 if (HadError)
4842 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004843}
4844
Richard Smithbd305122012-12-11 01:14:52 +00004845/// Check whether the exception specification provided for an
4846/// explicitly-defaulted special member matches the exception specification
4847/// that would have been generated for an implicit special member, per
4848/// C++11 [dcl.fct.def.default]p2.
4849void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4850 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4851 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004852 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4853 /*IsCXXMethod=*/true);
4854 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004855 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4856 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004857 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004858
4859 // Ensure that it matches.
4860 CheckEquivalentExceptionSpec(
4861 PDiag(diag::err_incorrect_defaulted_exception_spec)
4862 << getSpecialMember(MD), PDiag(),
4863 ImplicitType, SourceLocation(),
4864 SpecifiedType, MD->getLocation());
4865}
4866
Alp Tokerae3a9442013-10-18 05:54:19 +00004867void Sema::CheckDelayedMemberExceptionSpecs() {
4868 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4869 2> Checks;
4870 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004871
Alp Tokerae3a9442013-10-18 05:54:19 +00004872 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4873 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4874
4875 // Perform any deferred checking of exception specifications for virtual
4876 // destructors.
4877 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4878 const CXXDestructorDecl *Dtor = Checks[i].first;
4879 assert(!Dtor->getParent()->isDependentType() &&
4880 "Should not ever add destructors of templates into the list.");
4881 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4882 }
4883
4884 // Check that any explicitly-defaulted methods have exception specifications
4885 // compatible with their implicit exception specifications.
4886 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4887 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4888 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004889}
4890
Richard Smithd951a1d2012-02-18 02:02:13 +00004891namespace {
4892struct SpecialMemberDeletionInfo {
4893 Sema &S;
4894 CXXMethodDecl *MD;
4895 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004896 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004897
4898 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004899 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004900 SourceLocation Loc;
4901
4902 bool AllFieldsAreConst;
4903
4904 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004905 Sema::CXXSpecialMember CSM, bool Diagnose)
4906 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004907 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004908 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004909 AllFieldsAreConst(true) {
4910 switch (CSM) {
4911 case Sema::CXXDefaultConstructor:
4912 case Sema::CXXCopyConstructor:
4913 IsConstructor = true;
4914 break;
4915 case Sema::CXXMoveConstructor:
4916 IsConstructor = true;
4917 IsMove = true;
4918 break;
4919 case Sema::CXXCopyAssignment:
4920 IsAssignment = true;
4921 break;
4922 case Sema::CXXMoveAssignment:
4923 IsAssignment = true;
4924 IsMove = true;
4925 break;
4926 case Sema::CXXDestructor:
4927 break;
4928 case Sema::CXXInvalid:
4929 llvm_unreachable("invalid special member kind");
4930 }
4931
4932 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004933 if (const ReferenceType *RT =
4934 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4935 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004936 }
4937 }
4938
4939 bool inUnion() const { return MD->getParent()->isUnion(); }
4940
4941 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004942 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004943 unsigned Quals, bool IsMutable) {
4944 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4945 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004946 }
4947
Richard Smith852265f2012-03-30 20:53:28 +00004948 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004949
Richard Smith852265f2012-03-30 20:53:28 +00004950 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004951 bool shouldDeleteForField(FieldDecl *FD);
4952 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004953
Richard Smithaf136f82012-07-18 03:51:16 +00004954 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4955 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004956 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4957 Sema::SpecialMemberOverloadResult *SMOR,
4958 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004959
4960 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004961};
4962}
4963
John McCalld4274212012-04-09 20:53:23 +00004964/// Is the given special member inaccessible when used on the given
4965/// sub-object.
4966bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4967 CXXMethodDecl *target) {
4968 /// If we're operating on a base class, the object type is the
4969 /// type of this special member.
4970 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004971 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00004972 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4973 objectTy = S.Context.getTypeDeclType(MD->getParent());
4974 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4975
4976 // If we're operating on a field, the object type is the type of the field.
4977 } else {
4978 objectTy = S.Context.getTypeDeclType(target->getParent());
4979 }
4980
4981 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4982}
4983
Richard Smith852265f2012-03-30 20:53:28 +00004984/// Check whether we should delete a special member due to the implicit
4985/// definition containing a call to a special member of a subobject.
4986bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4987 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4988 bool IsDtorCallInCtor) {
4989 CXXMethodDecl *Decl = SMOR->getMethod();
4990 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4991
4992 int DiagKind = -1;
4993
4994 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4995 DiagKind = !Decl ? 0 : 1;
4996 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4997 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00004998 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00004999 DiagKind = 3;
5000 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5001 !Decl->isTrivial()) {
5002 // A member of a union must have a trivial corresponding special member.
5003 // As a weird special case, a destructor call from a union's constructor
5004 // must be accessible and non-deleted, but need not be trivial. Such a
5005 // destructor is never actually called, but is semantically checked as
5006 // if it were.
5007 DiagKind = 4;
5008 }
5009
5010 if (DiagKind == -1)
5011 return false;
5012
5013 if (Diagnose) {
5014 if (Field) {
5015 S.Diag(Field->getLocation(),
5016 diag::note_deleted_special_member_class_subobject)
5017 << CSM << MD->getParent() << /*IsField*/true
5018 << Field << DiagKind << IsDtorCallInCtor;
5019 } else {
5020 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5021 S.Diag(Base->getLocStart(),
5022 diag::note_deleted_special_member_class_subobject)
5023 << CSM << MD->getParent() << /*IsField*/false
5024 << Base->getType() << DiagKind << IsDtorCallInCtor;
5025 }
5026
5027 if (DiagKind == 1)
5028 S.NoteDeletedFunction(Decl);
5029 // FIXME: Explain inaccessibility if DiagKind == 3.
5030 }
5031
5032 return true;
5033}
5034
Richard Smith921bd202012-02-26 09:11:52 +00005035/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005036/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005037bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005038 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005039 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005040 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005041
5042 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005043 // -- any direct or virtual base class, or non-static data member with no
5044 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005045 // either M has no default constructor or overload resolution as applied
5046 // to M's default constructor results in an ambiguity or in a function
5047 // that is deleted or inaccessible
5048 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5049 // -- a direct or virtual base class B that cannot be copied/moved because
5050 // overload resolution, as applied to B's corresponding special member,
5051 // results in an ambiguity or a function that is deleted or inaccessible
5052 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005053 // C++11 [class.dtor]p5:
5054 // -- any direct or virtual base class [...] has a type with a destructor
5055 // that is deleted or inaccessible
5056 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005057 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005058 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5059 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005060 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005061
Richard Smith852265f2012-03-30 20:53:28 +00005062 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5063 // -- any direct or virtual base class or non-static data member has a
5064 // type with a destructor that is deleted or inaccessible
5065 if (IsConstructor) {
5066 Sema::SpecialMemberOverloadResult *SMOR =
5067 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5068 false, false, false, false, false);
5069 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5070 return true;
5071 }
5072
Richard Smith921bd202012-02-26 09:11:52 +00005073 return false;
5074}
5075
5076/// Check whether we should delete a special member function due to the class
5077/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005078bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005079 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005080 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005081}
5082
5083/// Check whether we should delete a special member function due to the class
5084/// having a particular non-static data member.
5085bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5086 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5087 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5088
5089 if (CSM == Sema::CXXDefaultConstructor) {
5090 // For a default constructor, all references must be initialized in-class
5091 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005092 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5093 if (Diagnose)
5094 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5095 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005096 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005097 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005098 // C++11 [class.ctor]p5: any non-variant non-static data member of
5099 // const-qualified type (or array thereof) with no
5100 // brace-or-equal-initializer does not have a user-provided default
5101 // constructor.
5102 if (!inUnion() && FieldType.isConstQualified() &&
5103 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005104 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5105 if (Diagnose)
5106 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005107 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005108 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005109 }
5110
5111 if (inUnion() && !FieldType.isConstQualified())
5112 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005113 } else if (CSM == Sema::CXXCopyConstructor) {
5114 // For a copy constructor, data members must not be of rvalue reference
5115 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005116 if (FieldType->isRValueReferenceType()) {
5117 if (Diagnose)
5118 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5119 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005120 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005121 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005122 } else if (IsAssignment) {
5123 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005124 if (FieldType->isReferenceType()) {
5125 if (Diagnose)
5126 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5127 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005128 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005129 }
5130 if (!FieldRecord && FieldType.isConstQualified()) {
5131 // C++11 [class.copy]p23:
5132 // -- a non-static data member of const non-class type (or array thereof)
5133 if (Diagnose)
5134 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005135 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005136 return true;
5137 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005138 }
5139
5140 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005141 // Some additional restrictions exist on the variant members.
5142 if (!inUnion() && FieldRecord->isUnion() &&
5143 FieldRecord->isAnonymousStructOrUnion()) {
5144 bool AllVariantFieldsAreConst = true;
5145
Richard Smith5704fe82012-03-29 19:00:10 +00005146 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00005147 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5148 UE = FieldRecord->field_end();
5149 UI != UE; ++UI) {
5150 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005151
5152 if (!UnionFieldType.isConstQualified())
5153 AllVariantFieldsAreConst = false;
5154
Richard Smith921bd202012-02-26 09:11:52 +00005155 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5156 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00005157 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5158 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005159 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005160 }
5161
5162 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005163 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00005164 FieldRecord->field_begin() != FieldRecord->field_end()) {
5165 if (Diagnose)
5166 S.Diag(FieldRecord->getLocation(),
5167 diag::note_deleted_default_ctor_all_const)
5168 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005169 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005170 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005171
Richard Smith5704fe82012-03-29 19:00:10 +00005172 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005173 // This is technically non-conformant, but sanity demands it.
5174 return false;
5175 }
5176
Richard Smithaf136f82012-07-18 03:51:16 +00005177 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5178 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005179 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005180 }
5181
5182 return false;
5183}
5184
5185/// C++11 [class.ctor] p5:
5186/// A defaulted default constructor for a class X is defined as deleted if
5187/// X is a union and all of its variant members are of const-qualified type.
5188bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005189 // This is a silly definition, because it gives an empty union a deleted
5190 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005191 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5192 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5193 if (Diagnose)
5194 S.Diag(MD->getParent()->getLocation(),
5195 diag::note_deleted_default_ctor_all_const)
5196 << MD->getParent() << /*not anonymous union*/0;
5197 return true;
5198 }
5199 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005200}
5201
5202/// Determine whether a defaulted special member function should be defined as
5203/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5204/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005205bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5206 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005207 if (MD->isInvalidDecl())
5208 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005209 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005210 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005211 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005212 return false;
5213
Richard Smithd951a1d2012-02-18 02:02:13 +00005214 // C++11 [expr.lambda.prim]p19:
5215 // The closure type associated with a lambda-expression has a
5216 // deleted (8.4.3) default constructor and a deleted copy
5217 // assignment operator.
5218 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005219 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5220 if (Diagnose)
5221 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005222 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005223 }
5224
Richard Smith6f1e2c62012-04-02 20:59:25 +00005225 // For an anonymous struct or union, the copy and assignment special members
5226 // will never be used, so skip the check. For an anonymous union declared at
5227 // namespace scope, the constructor and destructor are used.
5228 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5229 RD->isAnonymousStructOrUnion())
5230 return false;
5231
Richard Smith852265f2012-03-30 20:53:28 +00005232 // C++11 [class.copy]p7, p18:
5233 // If the class definition declares a move constructor or move assignment
5234 // operator, an implicitly declared copy constructor or copy assignment
5235 // operator is defined as deleted.
5236 if (MD->isImplicit() &&
5237 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5238 CXXMethodDecl *UserDeclaredMove = 0;
5239
5240 // In Microsoft mode, a user-declared move only causes the deletion of the
5241 // corresponding copy operation, not both copy operations.
5242 if (RD->hasUserDeclaredMoveConstructor() &&
5243 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5244 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005245
5246 // Find any user-declared move constructor.
5247 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5248 E = RD->ctor_end(); I != E; ++I) {
5249 if (I->isMoveConstructor()) {
5250 UserDeclaredMove = *I;
5251 break;
5252 }
5253 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005254 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005255 } else if (RD->hasUserDeclaredMoveAssignment() &&
5256 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5257 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005258
5259 // Find any user-declared move assignment operator.
5260 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5261 E = RD->method_end(); I != E; ++I) {
5262 if (I->isMoveAssignmentOperator()) {
5263 UserDeclaredMove = *I;
5264 break;
5265 }
5266 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005267 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005268 }
5269
5270 if (UserDeclaredMove) {
5271 Diag(UserDeclaredMove->getLocation(),
5272 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005273 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005274 << UserDeclaredMove->isMoveAssignmentOperator();
5275 return true;
5276 }
5277 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005278
Richard Smith6f1e2c62012-04-02 20:59:25 +00005279 // Do access control from the special member function
5280 ContextRAII MethodContext(*this, MD);
5281
Richard Smith921bd202012-02-26 09:11:52 +00005282 // C++11 [class.dtor]p5:
5283 // -- for a virtual destructor, lookup of the non-array deallocation function
5284 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005285 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005286 FunctionDecl *OperatorDelete = 0;
5287 DeclarationName Name =
5288 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5289 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005290 OperatorDelete, false)) {
5291 if (Diagnose)
5292 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005293 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005294 }
Richard Smith921bd202012-02-26 09:11:52 +00005295 }
5296
Richard Smith852265f2012-03-30 20:53:28 +00005297 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005298
Alexis Huntea6f0322011-05-11 22:34:38 +00005299 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005300 BE = RD->bases_end(); BI != BE; ++BI)
5301 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005302 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005303 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005304
Richard Smithd1627032013-07-22 18:06:23 +00005305 // Per DR1611, do not consider virtual bases of constructors of abstract
5306 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005307 if (!RD->isAbstract() || !SMI.IsConstructor) {
5308 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5309 BE = RD->vbases_end();
5310 BI != BE; ++BI)
5311 if (SMI.shouldDeleteForBase(BI))
5312 return true;
5313 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005314
5315 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005316 FE = RD->field_end(); FI != FE; ++FI)
5317 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005318 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005319 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005320
Richard Smithd951a1d2012-02-18 02:02:13 +00005321 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005322 return true;
5323
5324 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005325}
5326
Richard Smith92f241f2012-12-08 02:53:02 +00005327/// Perform lookup for a special member of the specified kind, and determine
5328/// whether it is trivial. If the triviality can be determined without the
5329/// lookup, skip it. This is intended for use when determining whether a
5330/// special member of a containing object is trivial, and thus does not ever
5331/// perform overload resolution for default constructors.
5332///
5333/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5334/// member that was most likely to be intended to be trivial, if any.
5335static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5336 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005337 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005338 if (Selected)
5339 *Selected = 0;
5340
5341 switch (CSM) {
5342 case Sema::CXXInvalid:
5343 llvm_unreachable("not a special member");
5344
5345 case Sema::CXXDefaultConstructor:
5346 // C++11 [class.ctor]p5:
5347 // A default constructor is trivial if:
5348 // - all the [direct subobjects] have trivial default constructors
5349 //
5350 // Note, no overload resolution is performed in this case.
5351 if (RD->hasTrivialDefaultConstructor())
5352 return true;
5353
5354 if (Selected) {
5355 // If there's a default constructor which could have been trivial, dig it
5356 // out. Otherwise, if there's any user-provided default constructor, point
5357 // to that as an example of why there's not a trivial one.
5358 CXXConstructorDecl *DefCtor = 0;
5359 if (RD->needsImplicitDefaultConstructor())
5360 S.DeclareImplicitDefaultConstructor(RD);
5361 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5362 CE = RD->ctor_end(); CI != CE; ++CI) {
5363 if (!CI->isDefaultConstructor())
5364 continue;
5365 DefCtor = *CI;
5366 if (!DefCtor->isUserProvided())
5367 break;
5368 }
5369
5370 *Selected = DefCtor;
5371 }
5372
5373 return false;
5374
5375 case Sema::CXXDestructor:
5376 // C++11 [class.dtor]p5:
5377 // A destructor is trivial if:
5378 // - all the direct [subobjects] have trivial destructors
5379 if (RD->hasTrivialDestructor())
5380 return true;
5381
5382 if (Selected) {
5383 if (RD->needsImplicitDestructor())
5384 S.DeclareImplicitDestructor(RD);
5385 *Selected = RD->getDestructor();
5386 }
5387
5388 return false;
5389
5390 case Sema::CXXCopyConstructor:
5391 // C++11 [class.copy]p12:
5392 // A copy constructor is trivial if:
5393 // - the constructor selected to copy each direct [subobject] is trivial
5394 if (RD->hasTrivialCopyConstructor()) {
5395 if (Quals == Qualifiers::Const)
5396 // We must either select the trivial copy constructor or reach an
5397 // ambiguity; no need to actually perform overload resolution.
5398 return true;
5399 } else if (!Selected) {
5400 return false;
5401 }
5402 // In C++98, we are not supposed to perform overload resolution here, but we
5403 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5404 // cases like B as having a non-trivial copy constructor:
5405 // struct A { template<typename T> A(T&); };
5406 // struct B { mutable A a; };
5407 goto NeedOverloadResolution;
5408
5409 case Sema::CXXCopyAssignment:
5410 // C++11 [class.copy]p25:
5411 // A copy assignment operator is trivial if:
5412 // - the assignment operator selected to copy each direct [subobject] is
5413 // trivial
5414 if (RD->hasTrivialCopyAssignment()) {
5415 if (Quals == Qualifiers::Const)
5416 return true;
5417 } else if (!Selected) {
5418 return false;
5419 }
5420 // In C++98, we are not supposed to perform overload resolution here, but we
5421 // treat that as a language defect.
5422 goto NeedOverloadResolution;
5423
5424 case Sema::CXXMoveConstructor:
5425 case Sema::CXXMoveAssignment:
5426 NeedOverloadResolution:
5427 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005428 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005429
5430 // The standard doesn't describe how to behave if the lookup is ambiguous.
5431 // We treat it as not making the member non-trivial, just like the standard
5432 // mandates for the default constructor. This should rarely matter, because
5433 // the member will also be deleted.
5434 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5435 return true;
5436
5437 if (!SMOR->getMethod()) {
5438 assert(SMOR->getKind() ==
5439 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5440 return false;
5441 }
5442
5443 // We deliberately don't check if we found a deleted special member. We're
5444 // not supposed to!
5445 if (Selected)
5446 *Selected = SMOR->getMethod();
5447 return SMOR->getMethod()->isTrivial();
5448 }
5449
5450 llvm_unreachable("unknown special method kind");
5451}
5452
Benjamin Kramer3e350262013-02-15 12:30:38 +00005453static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005454 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5455 CI != CE; ++CI)
5456 if (!CI->isImplicit())
5457 return *CI;
5458
5459 // Look for constructor templates.
5460 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5461 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5462 if (CXXConstructorDecl *CD =
5463 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5464 return CD;
5465 }
5466
5467 return 0;
5468}
5469
5470/// The kind of subobject we are checking for triviality. The values of this
5471/// enumeration are used in diagnostics.
5472enum TrivialSubobjectKind {
5473 /// The subobject is a base class.
5474 TSK_BaseClass,
5475 /// The subobject is a non-static data member.
5476 TSK_Field,
5477 /// The object is actually the complete object.
5478 TSK_CompleteObject
5479};
5480
5481/// Check whether the special member selected for a given type would be trivial.
5482static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005483 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005484 Sema::CXXSpecialMember CSM,
5485 TrivialSubobjectKind Kind,
5486 bool Diagnose) {
5487 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5488 if (!SubRD)
5489 return true;
5490
5491 CXXMethodDecl *Selected;
5492 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005493 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005494 return true;
5495
5496 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005497 if (ConstRHS)
5498 SubType.addConst();
5499
Richard Smith92f241f2012-12-08 02:53:02 +00005500 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5501 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5502 << Kind << SubType.getUnqualifiedType();
5503 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5504 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5505 } else if (!Selected)
5506 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5507 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5508 else if (Selected->isUserProvided()) {
5509 if (Kind == TSK_CompleteObject)
5510 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5511 << Kind << SubType.getUnqualifiedType() << CSM;
5512 else {
5513 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5514 << Kind << SubType.getUnqualifiedType() << CSM;
5515 S.Diag(Selected->getLocation(), diag::note_declared_at);
5516 }
5517 } else {
5518 if (Kind != TSK_CompleteObject)
5519 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5520 << Kind << SubType.getUnqualifiedType() << CSM;
5521
5522 // Explain why the defaulted or deleted special member isn't trivial.
5523 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5524 }
5525 }
5526
5527 return false;
5528}
5529
5530/// Check whether the members of a class type allow a special member to be
5531/// trivial.
5532static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5533 Sema::CXXSpecialMember CSM,
5534 bool ConstArg, bool Diagnose) {
5535 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5536 FE = RD->field_end(); FI != FE; ++FI) {
5537 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5538 continue;
5539
5540 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5541
5542 // Pretend anonymous struct or union members are members of this class.
5543 if (FI->isAnonymousStructOrUnion()) {
5544 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5545 CSM, ConstArg, Diagnose))
5546 return false;
5547 continue;
5548 }
5549
5550 // C++11 [class.ctor]p5:
5551 // A default constructor is trivial if [...]
5552 // -- no non-static data member of its class has a
5553 // brace-or-equal-initializer
5554 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5555 if (Diagnose)
5556 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5557 return false;
5558 }
5559
5560 // Objective C ARC 4.3.5:
5561 // [...] nontrivally ownership-qualified types are [...] not trivially
5562 // default constructible, copy constructible, move constructible, copy
5563 // assignable, move assignable, or destructible [...]
5564 if (S.getLangOpts().ObjCAutoRefCount &&
5565 FieldType.hasNonTrivialObjCLifetime()) {
5566 if (Diagnose)
5567 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5568 << RD << FieldType.getObjCLifetime();
5569 return false;
5570 }
5571
Richard Smith41c35d62013-11-27 03:39:20 +00005572 bool ConstRHS = ConstArg && !FI->isMutable();
5573 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5574 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005575 return false;
5576 }
5577
5578 return true;
5579}
5580
5581/// Diagnose why the specified class does not have a trivial special member of
5582/// the given kind.
5583void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5584 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005585
Richard Smith41c35d62013-11-27 03:39:20 +00005586 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5587 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005588 TSK_CompleteObject, /*Diagnose*/true);
5589}
5590
5591/// Determine whether a defaulted or deleted special member function is trivial,
5592/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5593/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5594bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5595 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005596 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5597
5598 CXXRecordDecl *RD = MD->getParent();
5599
5600 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005601
Richard Smith2002bfe2013-11-04 02:02:27 +00005602 // C++11 [class.copy]p12, p25: [DR1593]
5603 // A [special member] is trivial if [...] its parameter-type-list is
5604 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005605 switch (CSM) {
5606 case CXXDefaultConstructor:
5607 case CXXDestructor:
5608 // Trivial default constructors and destructors cannot have parameters.
5609 break;
5610
5611 case CXXCopyConstructor:
5612 case CXXCopyAssignment: {
5613 // Trivial copy operations always have const, non-volatile parameter types.
5614 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005615 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005616 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5617 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5618 if (Diagnose)
5619 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5620 << Param0->getSourceRange() << Param0->getType()
5621 << Context.getLValueReferenceType(
5622 Context.getRecordType(RD).withConst());
5623 return false;
5624 }
5625 break;
5626 }
5627
5628 case CXXMoveConstructor:
5629 case CXXMoveAssignment: {
5630 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005631 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005632 const RValueReferenceType *RT =
5633 Param0->getType()->getAs<RValueReferenceType>();
5634 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5635 if (Diagnose)
5636 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5637 << Param0->getSourceRange() << Param0->getType()
5638 << Context.getRValueReferenceType(Context.getRecordType(RD));
5639 return false;
5640 }
5641 break;
5642 }
5643
5644 case CXXInvalid:
5645 llvm_unreachable("not a special member");
5646 }
5647
Richard Smith92f241f2012-12-08 02:53:02 +00005648 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5649 if (Diagnose)
5650 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5651 diag::note_nontrivial_default_arg)
5652 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5653 return false;
5654 }
5655 if (MD->isVariadic()) {
5656 if (Diagnose)
5657 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5658 return false;
5659 }
5660
5661 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5662 // A copy/move [constructor or assignment operator] is trivial if
5663 // -- the [member] selected to copy/move each direct base class subobject
5664 // is trivial
5665 //
5666 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5667 // A [default constructor or destructor] is trivial if
5668 // -- all the direct base classes have trivial [default constructors or
5669 // destructors]
5670 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5671 BE = RD->bases_end(); BI != BE; ++BI)
Richard Smith41c35d62013-11-27 03:39:20 +00005672 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(),
5673 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005674 return false;
5675
5676 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5677 // A copy/move [constructor or assignment operator] for a class X is
5678 // trivial if
5679 // -- for each non-static data member of X that is of class type (or array
5680 // thereof), the constructor selected to copy/move that member is
5681 // trivial
5682 //
5683 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5684 // A [default constructor or destructor] is trivial if
5685 // -- for all of the non-static data members of its class that are of class
5686 // type (or array thereof), each such class has a trivial [default
5687 // constructor or destructor]
5688 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5689 return false;
5690
5691 // C++11 [class.dtor]p5:
5692 // A destructor is trivial if [...]
5693 // -- the destructor is not virtual
5694 if (CSM == CXXDestructor && MD->isVirtual()) {
5695 if (Diagnose)
5696 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5697 return false;
5698 }
5699
5700 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5701 // A [special member] for class X is trivial if [...]
5702 // -- class X has no virtual functions and no virtual base classes
5703 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5704 if (!Diagnose)
5705 return false;
5706
5707 if (RD->getNumVBases()) {
5708 // Check for virtual bases. We already know that the corresponding
5709 // member in all bases is trivial, so vbases must all be direct.
5710 CXXBaseSpecifier &BS = *RD->vbases_begin();
5711 assert(BS.isVirtual());
5712 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5713 return false;
5714 }
5715
5716 // Must have a virtual method.
5717 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5718 ME = RD->method_end(); MI != ME; ++MI) {
5719 if (MI->isVirtual()) {
5720 SourceLocation MLoc = MI->getLocStart();
5721 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5722 return false;
5723 }
5724 }
5725
5726 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5727 }
5728
5729 // Looks like it's trivial!
5730 return true;
5731}
5732
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005733/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005734namespace {
5735 struct FindHiddenVirtualMethodData {
5736 Sema *S;
5737 CXXMethodDecl *Method;
5738 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005739 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005740 };
5741}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005742
David Blaikie282c92a2012-10-19 00:53:08 +00005743/// \brief Check whether any most overriden method from MD in Methods
5744static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5745 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5746 if (MD->size_overridden_methods() == 0)
5747 return Methods.count(MD->getCanonicalDecl());
5748 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5749 E = MD->end_overridden_methods();
5750 I != E; ++I)
5751 if (CheckMostOverridenMethods(*I, Methods))
5752 return true;
5753 return false;
5754}
5755
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005756/// \brief Member lookup function that determines whether a given C++
5757/// method overloads virtual methods in a base class without overriding any,
5758/// to be used with CXXRecordDecl::lookupInBases().
5759static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5760 CXXBasePath &Path,
5761 void *UserData) {
5762 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5763
5764 FindHiddenVirtualMethodData &Data
5765 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5766
5767 DeclarationName Name = Data.Method->getDeclName();
5768 assert(Name.getNameKind() == DeclarationName::Identifier);
5769
5770 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005771 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005772 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005773 !Path.Decls.empty();
5774 Path.Decls = Path.Decls.slice(1)) {
5775 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005776 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005777 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005778 foundSameNameMethod = true;
5779 // Interested only in hidden virtual methods.
5780 if (!MD->isVirtual())
5781 continue;
5782 // If the method we are checking overrides a method from its base
5783 // don't warn about the other overloaded methods.
5784 if (!Data.S->IsOverload(Data.Method, MD, false))
5785 return true;
5786 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005787 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005788 overloadedMethods.push_back(MD);
5789 }
5790 }
5791
5792 if (foundSameNameMethod)
5793 Data.OverloadedMethods.append(overloadedMethods.begin(),
5794 overloadedMethods.end());
5795 return foundSameNameMethod;
5796}
5797
David Blaikie282c92a2012-10-19 00:53:08 +00005798/// \brief Add the most overriden methods from MD to Methods
5799static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5800 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5801 if (MD->size_overridden_methods() == 0)
5802 Methods.insert(MD->getCanonicalDecl());
5803 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5804 E = MD->end_overridden_methods();
5805 I != E; ++I)
5806 AddMostOverridenMethods(*I, Methods);
5807}
5808
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005809/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005810/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005811void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5812 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005813 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005814 return;
5815
5816 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5817 /*bool RecordPaths=*/false,
5818 /*bool DetectVirtual=*/false);
5819 FindHiddenVirtualMethodData Data;
5820 Data.Method = MD;
5821 Data.S = this;
5822
5823 // Keep the base methods that were overriden or introduced in the subclass
5824 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005825 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005826 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5827 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5828 NamedDecl *ND = *I;
5829 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005830 ND = shad->getTargetDecl();
5831 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5832 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005833 }
5834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005835 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5836 OverloadedMethods = Data.OverloadedMethods;
5837}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005838
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005839void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5840 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5841 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5842 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5843 PartialDiagnostic PD = PDiag(
5844 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5845 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5846 Diag(overloadedMD->getLocation(), PD);
5847 }
5848}
5849
5850/// \brief Diagnose methods which overload virtual methods in a base class
5851/// without overriding any.
5852void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5853 if (MD->isInvalidDecl())
5854 return;
5855
5856 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5857 MD->getLocation()) == DiagnosticsEngine::Ignored)
5858 return;
5859
5860 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5861 FindHiddenVirtualMethods(MD, OverloadedMethods);
5862 if (!OverloadedMethods.empty()) {
5863 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5864 << MD << (OverloadedMethods.size() > 1);
5865
5866 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005867 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005868}
5869
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005870void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005871 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005872 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005873 SourceLocation RBrac,
5874 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005875 if (!TagDecl)
5876 return;
Mike Stump11289f42009-09-09 15:08:12 +00005877
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005878 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005879
Rafael Espindola06e1b132012-07-12 04:32:30 +00005880 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5881 if (l->getKind() != AttributeList::AT_Visibility)
5882 continue;
5883 l->setInvalid();
5884 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5885 l->getName();
5886 }
5887
David Blaikie751c5582011-09-22 02:58:26 +00005888 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005889 // strict aliasing violation!
5890 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005891 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005892
Douglas Gregor0be31a22010-07-02 17:43:08 +00005893 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005894 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005895}
5896
Douglas Gregor05379422008-11-03 17:51:48 +00005897/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5898/// special functions, such as the default constructor, copy
5899/// constructor, or destructor, to the given C++ class (C++
5900/// [special]p1). This routine can only be executed just before the
5901/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005902void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005903 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005904 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005905
Richard Smith6b02d462012-12-08 08:32:28 +00005906 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005907 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005908
Richard Smith6b02d462012-12-08 08:32:28 +00005909 // If the properties or semantics of the copy constructor couldn't be
5910 // determined while the class was being declared, force a declaration
5911 // of it now.
5912 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5913 DeclareImplicitCopyConstructor(ClassDecl);
5914 }
5915
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005916 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005917 ++ASTContext::NumImplicitMoveConstructors;
5918
Richard Smith6b02d462012-12-08 08:32:28 +00005919 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5920 DeclareImplicitMoveConstructor(ClassDecl);
5921 }
5922
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005923 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5924 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005925
5926 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005927 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005928 // it shows up in the right place in the vtable and that we diagnose
5929 // problems with the implicit exception specification.
5930 if (ClassDecl->isDynamicClass() ||
5931 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005932 DeclareImplicitCopyAssignment(ClassDecl);
5933 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005934
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005935 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005936 ++ASTContext::NumImplicitMoveAssignmentOperators;
5937
5938 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005939 if (ClassDecl->isDynamicClass() ||
5940 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005941 DeclareImplicitMoveAssignment(ClassDecl);
5942 }
5943
Douglas Gregor7454c562010-07-02 20:37:36 +00005944 if (!ClassDecl->hasUserDeclaredDestructor()) {
5945 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005946
5947 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005948 // have to declare the destructor immediately. This ensures that, e.g., it
5949 // shows up in the right place in the vtable and that we diagnose problems
5950 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005951 if (ClassDecl->isDynamicClass() ||
5952 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005953 DeclareImplicitDestructor(ClassDecl);
5954 }
Douglas Gregor05379422008-11-03 17:51:48 +00005955}
5956
Francois Pichet1c229c02011-04-22 22:18:13 +00005957void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5958 if (!D)
5959 return;
5960
5961 int NumParamList = D->getNumTemplateParameterLists();
5962 for (int i = 0; i < NumParamList; i++) {
5963 TemplateParameterList* Params = D->getTemplateParameterList(i);
5964 for (TemplateParameterList::iterator Param = Params->begin(),
5965 ParamEnd = Params->end();
5966 Param != ParamEnd; ++Param) {
5967 NamedDecl *Named = cast<NamedDecl>(*Param);
5968 if (Named->getDeclName()) {
5969 S->AddDecl(Named);
5970 IdResolver.AddDecl(Named);
5971 }
5972 }
5973 }
5974}
5975
John McCall48871652010-08-21 09:40:31 +00005976void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005977 if (!D)
5978 return;
5979
5980 TemplateParameterList *Params = 0;
5981 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5982 Params = Template->getTemplateParameters();
5983 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5984 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5985 Params = PartialSpec->getTemplateParameters();
5986 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005987 return;
5988
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005989 for (TemplateParameterList::iterator Param = Params->begin(),
5990 ParamEnd = Params->end();
5991 Param != ParamEnd; ++Param) {
5992 NamedDecl *Named = cast<NamedDecl>(*Param);
5993 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005994 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005995 IdResolver.AddDecl(Named);
5996 }
5997 }
5998}
5999
John McCall48871652010-08-21 09:40:31 +00006000void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006001 if (!RecordD) return;
6002 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006003 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006004 PushDeclContext(S, Record);
6005}
6006
John McCall48871652010-08-21 09:40:31 +00006007void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006008 if (!RecordD) return;
6009 PopDeclContext();
6010}
6011
Douglas Gregor4d87df52008-12-16 21:30:33 +00006012/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6013/// parsing a top-level (non-nested) C++ class, and we are now
6014/// parsing those parts of the given Method declaration that could
6015/// not be parsed earlier (C++ [class.mem]p2), such as default
6016/// arguments. This action should enter the scope of the given
6017/// Method declaration as if we had just parsed the qualified method
6018/// name. However, it should not bring the parameters into scope;
6019/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006020void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006021}
6022
6023/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6024/// C++ method declaration. We're (re-)introducing the given
6025/// function parameter into scope for use in parsing later parts of
6026/// the method declaration. For example, we could see an
6027/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006028void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006029 if (!ParamD)
6030 return;
Mike Stump11289f42009-09-09 15:08:12 +00006031
John McCall48871652010-08-21 09:40:31 +00006032 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006033
6034 // If this parameter has an unparsed default argument, clear it out
6035 // to make way for the parsed default argument.
6036 if (Param->hasUnparsedDefaultArg())
6037 Param->setDefaultArg(0);
6038
John McCall48871652010-08-21 09:40:31 +00006039 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006040 if (Param->getDeclName())
6041 IdResolver.AddDecl(Param);
6042}
6043
6044/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6045/// processing the delayed method declaration for Method. The method
6046/// declaration is now considered finished. There may be a separate
6047/// ActOnStartOfFunctionDef action later (not necessarily
6048/// immediately!) for this method, if it was also defined inside the
6049/// class body.
John McCall48871652010-08-21 09:40:31 +00006050void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006051 if (!MethodD)
6052 return;
Mike Stump11289f42009-09-09 15:08:12 +00006053
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006054 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006055
John McCall48871652010-08-21 09:40:31 +00006056 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006057
6058 // Now that we have our default arguments, check the constructor
6059 // again. It could produce additional diagnostics or affect whether
6060 // the class has implicitly-declared destructors, among other
6061 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006062 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6063 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006064
6065 // Check the default arguments, which we may have added.
6066 if (!Method->isInvalidDecl())
6067 CheckCXXDefaultArguments(Method);
6068}
6069
Douglas Gregor831c93f2008-11-05 20:51:48 +00006070/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006071/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006072/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006073/// emit diagnostics and set the invalid bit to true. In any case, the type
6074/// will be updated to reflect a well-formed type for the constructor and
6075/// returned.
6076QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006077 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006078 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006079
6080 // C++ [class.ctor]p3:
6081 // A constructor shall not be virtual (10.3) or static (9.4). A
6082 // constructor can be invoked for a const, volatile or const
6083 // volatile object. A constructor shall not be declared const,
6084 // volatile, or const volatile (9.3.2).
6085 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006086 if (!D.isInvalidType())
6087 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6088 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6089 << SourceRange(D.getIdentifierLoc());
6090 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006091 }
John McCall8e7d6562010-08-26 03:08:43 +00006092 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006093 if (!D.isInvalidType())
6094 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6095 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6096 << SourceRange(D.getIdentifierLoc());
6097 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006098 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006099 }
Mike Stump11289f42009-09-09 15:08:12 +00006100
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006101 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006102 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006103 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006104 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6105 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006106 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006107 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6108 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006109 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006110 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6111 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006112 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006113 }
Mike Stump11289f42009-09-09 15:08:12 +00006114
Douglas Gregordb9d6642011-01-26 05:01:58 +00006115 // C++0x [class.ctor]p4:
6116 // A constructor shall not be declared with a ref-qualifier.
6117 if (FTI.hasRefQualifier()) {
6118 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6119 << FTI.RefQualifierIsLValueRef
6120 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6121 D.setInvalidType();
6122 }
6123
Douglas Gregor831c93f2008-11-05 20:51:48 +00006124 // Rebuild the function type "R" without any type qualifiers (in
6125 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006126 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006127 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006128 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6129 return R;
6130
6131 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6132 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006133 EPI.RefQualifier = RQ_None;
6134
Richard Smithc2bc61b2013-03-18 21:12:30 +00006135 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006136}
6137
Douglas Gregor4d87df52008-12-16 21:30:33 +00006138/// CheckConstructor - Checks a fully-formed constructor for
6139/// well-formedness, issuing any diagnostics required. Returns true if
6140/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006141void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006142 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006143 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6144 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006145 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006146
6147 // C++ [class.copy]p3:
6148 // A declaration of a constructor for a class X is ill-formed if
6149 // its first parameter is of type (optionally cv-qualified) X and
6150 // either there are no other parameters or else all other
6151 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006152 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006153 ((Constructor->getNumParams() == 1) ||
6154 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006155 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6156 Constructor->getTemplateSpecializationKind()
6157 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006158 QualType ParamType = Constructor->getParamDecl(0)->getType();
6159 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6160 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006161 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006162 const char *ConstRef
6163 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6164 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006165 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006166 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006167
6168 // FIXME: Rather that making the constructor invalid, we should endeavor
6169 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006170 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006171 }
6172 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006173}
6174
John McCalldeb646e2010-08-04 01:04:25 +00006175/// CheckDestructor - Checks a fully-formed destructor definition for
6176/// well-formedness, issuing any diagnostics required. Returns true
6177/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006178bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006179 CXXRecordDecl *RD = Destructor->getParent();
6180
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006181 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006182 SourceLocation Loc;
6183
6184 if (!Destructor->isImplicit())
6185 Loc = Destructor->getLocation();
6186 else
6187 Loc = RD->getLocation();
6188
6189 // If we have a virtual destructor, look up the deallocation function
6190 FunctionDecl *OperatorDelete = 0;
6191 DeclarationName Name =
6192 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006193 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006194 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006195 // If there's no class-specific operator delete, look up the global
6196 // non-array delete.
6197 if (!OperatorDelete)
6198 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006199
Eli Friedmanfa0df832012-02-02 03:46:19 +00006200 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006201
6202 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006203 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006204
6205 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006206}
6207
Mike Stump11289f42009-09-09 15:08:12 +00006208static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006209FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6210 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6211 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006212 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006213}
6214
Douglas Gregor831c93f2008-11-05 20:51:48 +00006215/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6216/// the well-formednes of the destructor declarator @p D with type @p
6217/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006218/// emit diagnostics and set the declarator to invalid. Even if this happens,
6219/// will be updated to reflect a well-formed type for the destructor and
6220/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006221QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006222 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006223 // C++ [class.dtor]p1:
6224 // [...] A typedef-name that names a class is a class-name
6225 // (7.1.3); however, a typedef-name that names a class shall not
6226 // be used as the identifier in the declarator for a destructor
6227 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006228 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006229 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006230 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006231 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006232 else if (const TemplateSpecializationType *TST =
6233 DeclaratorType->getAs<TemplateSpecializationType>())
6234 if (TST->isTypeAlias())
6235 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6236 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006237
6238 // C++ [class.dtor]p2:
6239 // A destructor is used to destroy objects of its class type. A
6240 // destructor takes no parameters, and no return type can be
6241 // specified for it (not even void). The address of a destructor
6242 // shall not be taken. A destructor shall not be static. A
6243 // destructor can be invoked for a const, volatile or const
6244 // volatile object. A destructor shall not be declared const,
6245 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006246 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006247 if (!D.isInvalidType())
6248 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6249 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006250 << SourceRange(D.getIdentifierLoc())
6251 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6252
John McCall8e7d6562010-08-26 03:08:43 +00006253 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006254 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006255 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006256 // Destructors don't have return types, but the parser will
6257 // happily parse something like:
6258 //
6259 // class X {
6260 // float ~X();
6261 // };
6262 //
6263 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006264 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6265 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6266 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006267 }
Mike Stump11289f42009-09-09 15:08:12 +00006268
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006269 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006270 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006271 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006272 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6273 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006274 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006275 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6276 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006277 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006278 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6279 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006280 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006281 }
6282
Douglas Gregordb9d6642011-01-26 05:01:58 +00006283 // C++0x [class.dtor]p2:
6284 // A destructor shall not be declared with a ref-qualifier.
6285 if (FTI.hasRefQualifier()) {
6286 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6287 << FTI.RefQualifierIsLValueRef
6288 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6289 D.setInvalidType();
6290 }
6291
Douglas Gregor831c93f2008-11-05 20:51:48 +00006292 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00006293 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006294 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6295
6296 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00006297 FTI.freeArgs();
6298 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006299 }
6300
Mike Stump11289f42009-09-09 15:08:12 +00006301 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006302 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006303 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006304 D.setInvalidType();
6305 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006306
6307 // Rebuild the function type "R" without any type qualifiers or
6308 // parameters (in case any of the errors above fired) and with
6309 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006310 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006311 if (!D.isInvalidType())
6312 return R;
6313
Douglas Gregor95755162010-07-01 05:10:53 +00006314 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006315 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6316 EPI.Variadic = false;
6317 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006318 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006319 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006320}
6321
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006322/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6323/// well-formednes of the conversion function declarator @p D with
6324/// type @p R. If there are any errors in the declarator, this routine
6325/// will emit diagnostics and return true. Otherwise, it will return
6326/// false. Either way, the type @p R will be updated to reflect a
6327/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006328void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006329 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006330 // C++ [class.conv.fct]p1:
6331 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006332 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006333 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006334 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006335 if (!D.isInvalidType())
6336 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006337 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6338 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006339 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006340 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006341 }
John McCall212fa2e2010-04-13 00:04:31 +00006342
6343 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6344
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006345 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006346 // Conversion functions don't have return types, but the parser will
6347 // happily parse something like:
6348 //
6349 // class X {
6350 // float operator bool();
6351 // };
6352 //
6353 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006354 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6355 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6356 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006357 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006358 }
6359
John McCall212fa2e2010-04-13 00:04:31 +00006360 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6361
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006362 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00006363 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006364 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6365
6366 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006367 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006368 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006369 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006370 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006371 D.setInvalidType();
6372 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006373
John McCall212fa2e2010-04-13 00:04:31 +00006374 // Diagnose "&operator bool()" and other such nonsense. This
6375 // is actually a gcc extension which we don't support.
6376 if (Proto->getResultType() != ConvType) {
6377 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6378 << Proto->getResultType();
6379 D.setInvalidType();
6380 ConvType = Proto->getResultType();
6381 }
6382
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006383 // C++ [class.conv.fct]p4:
6384 // The conversion-type-id shall not represent a function type nor
6385 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006386 if (ConvType->isArrayType()) {
6387 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6388 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006389 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006390 } else if (ConvType->isFunctionType()) {
6391 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6392 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006393 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006394 }
6395
6396 // Rebuild the function type "R" without any parameters (in case any
6397 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006398 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006399 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006400 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006401
Douglas Gregor5fb53972009-01-14 15:45:31 +00006402 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006403 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006404 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006405 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006406 diag::warn_cxx98_compat_explicit_conversion_functions :
6407 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006408 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006409}
6410
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006411/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6412/// the declaration of the given C++ conversion function. This routine
6413/// is responsible for recording the conversion function in the C++
6414/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006415Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006416 assert(Conversion && "Expected to receive a conversion function declaration");
6417
Douglas Gregor4287b372008-12-12 08:25:50 +00006418 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006419
6420 // Make sure we aren't redeclaring the conversion function.
6421 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006422
6423 // C++ [class.conv.fct]p1:
6424 // [...] A conversion function is never used to convert a
6425 // (possibly cv-qualified) object to the (possibly cv-qualified)
6426 // same object type (or a reference to it), to a (possibly
6427 // cv-qualified) base class of that type (or a reference to it),
6428 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006429 // FIXME: Suppress this warning if the conversion function ends up being a
6430 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006431 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006432 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006433 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006434 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006435 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6436 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006437 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006438 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006439 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6440 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006441 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006442 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006443 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006444 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006445 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006446 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006447 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006448 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006449 }
6450
Douglas Gregor457104e2010-09-29 04:25:11 +00006451 if (FunctionTemplateDecl *ConversionTemplate
6452 = Conversion->getDescribedFunctionTemplate())
6453 return ConversionTemplate;
6454
John McCall48871652010-08-21 09:40:31 +00006455 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006456}
6457
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006458//===----------------------------------------------------------------------===//
6459// Namespace Handling
6460//===----------------------------------------------------------------------===//
6461
Richard Smith45bb8852012-10-04 22:13:39 +00006462/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6463/// reopened.
6464static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6465 SourceLocation Loc,
6466 IdentifierInfo *II, bool *IsInline,
6467 NamespaceDecl *PrevNS) {
6468 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006469
Richard Smithf501cc32012-10-05 01:46:25 +00006470 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6471 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6472 // inline namespaces, with the intention of bringing names into namespace std.
6473 //
6474 // We support this just well enough to get that case working; this is not
6475 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006476 if (*IsInline && II && II->getName().startswith("__atomic") &&
6477 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006478 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006479 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6480 NS = NS->getPreviousDecl())
6481 NS->setInline(*IsInline);
6482 // Patch up the lookup table for the containing namespace. This isn't really
6483 // correct, but it's good enough for this particular case.
6484 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6485 E = PrevNS->decls_end(); I != E; ++I)
6486 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6487 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6488 return;
6489 }
6490
6491 if (PrevNS->isInline())
6492 // The user probably just forgot the 'inline', so suggest that it
6493 // be added back.
6494 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6495 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6496 else
6497 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6498 << IsInline;
6499
6500 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6501 *IsInline = PrevNS->isInline();
6502}
John McCallb1be5232010-08-26 09:15:37 +00006503
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006504/// ActOnStartNamespaceDef - This is called at the start of a namespace
6505/// definition.
John McCall48871652010-08-21 09:40:31 +00006506Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006507 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006508 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006509 SourceLocation IdentLoc,
6510 IdentifierInfo *II,
6511 SourceLocation LBrace,
6512 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006513 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6514 // For anonymous namespace, take the location of the left brace.
6515 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006516 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006517 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006518 bool IsStd = false;
6519 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006520 Scope *DeclRegionScope = NamespcScope->getParent();
6521
Douglas Gregore57e7522012-01-07 09:11:48 +00006522 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006523 if (II) {
6524 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006525 // The identifier in an original-namespace-definition shall not
6526 // have been previously defined in the declarative region in
6527 // which the original-namespace-definition appears. The
6528 // identifier in an original-namespace-definition is the name of
6529 // the namespace. Subsequently in that declarative region, it is
6530 // treated as an original-namespace-name.
6531 //
6532 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006533 // look through using directives, just look for any ordinary names.
6534
6535 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006536 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6537 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006538 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006539 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6540 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6541 ++I) {
6542 if ((*I)->getIdentifierNamespace() & IDNS) {
6543 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006544 break;
6545 }
6546 }
6547
Douglas Gregore57e7522012-01-07 09:11:48 +00006548 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6549
6550 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006551 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006552 if (IsInline != PrevNS->isInline())
6553 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6554 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006555 } else if (PrevDecl) {
6556 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006557 Diag(Loc, diag::err_redefinition_different_kind)
6558 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006559 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006560 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006561 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006562 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006563 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006564 // This is the first "real" definition of the namespace "std", so update
6565 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006566 PrevNS = getStdNamespace();
6567 IsStd = true;
6568 AddToKnown = !IsInline;
6569 } else {
6570 // We've seen this namespace for the first time.
6571 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006572 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006573 } else {
John McCall4fa53422009-10-01 00:25:31 +00006574 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006575
6576 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006577 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006578 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006579 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006580 } else {
6581 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006582 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006583 }
6584
Richard Smith45bb8852012-10-04 22:13:39 +00006585 if (PrevNS && IsInline != PrevNS->isInline())
6586 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6587 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006588 }
6589
6590 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6591 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006592 if (IsInvalid)
6593 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006594
6595 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006596
Douglas Gregore57e7522012-01-07 09:11:48 +00006597 // FIXME: Should we be merging attributes?
6598 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006599 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006600
6601 if (IsStd)
6602 StdNamespace = Namespc;
6603 if (AddToKnown)
6604 KnownNamespaces[Namespc] = false;
6605
6606 if (II) {
6607 PushOnScopeChains(Namespc, DeclRegionScope);
6608 } else {
6609 // Link the anonymous namespace into its parent.
6610 DeclContext *Parent = CurContext->getRedeclContext();
6611 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6612 TU->setAnonymousNamespace(Namespc);
6613 } else {
6614 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006615 }
John McCall4fa53422009-10-01 00:25:31 +00006616
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006617 CurContext->addDecl(Namespc);
6618
John McCall4fa53422009-10-01 00:25:31 +00006619 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6620 // behaves as if it were replaced by
6621 // namespace unique { /* empty body */ }
6622 // using namespace unique;
6623 // namespace unique { namespace-body }
6624 // where all occurrences of 'unique' in a translation unit are
6625 // replaced by the same identifier and this identifier differs
6626 // from all other identifiers in the entire program.
6627
6628 // We just create the namespace with an empty name and then add an
6629 // implicit using declaration, just like the standard suggests.
6630 //
6631 // CodeGen enforces the "universally unique" aspect by giving all
6632 // declarations semantically contained within an anonymous
6633 // namespace internal linkage.
6634
Douglas Gregore57e7522012-01-07 09:11:48 +00006635 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006636 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006637 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006638 /* 'using' */ LBrace,
6639 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006640 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006641 /* identifier */ SourceLocation(),
6642 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006643 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006644 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006645 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006646 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006647 }
6648
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006649 ActOnDocumentableDecl(Namespc);
6650
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006651 // Although we could have an invalid decl (i.e. the namespace name is a
6652 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006653 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6654 // for the namespace has the declarations that showed up in that particular
6655 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006656 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006657 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006658}
6659
Sebastian Redla6602e92009-11-23 15:34:23 +00006660/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6661/// is a namespace alias, returns the namespace it points to.
6662static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6663 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6664 return AD->getNamespace();
6665 return dyn_cast_or_null<NamespaceDecl>(D);
6666}
6667
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006668/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6669/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006670void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006671 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6672 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006673 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006674 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006675 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006676 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006677}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006678
John McCall28a0cf72010-08-25 07:42:41 +00006679CXXRecordDecl *Sema::getStdBadAlloc() const {
6680 return cast_or_null<CXXRecordDecl>(
6681 StdBadAlloc.get(Context.getExternalSource()));
6682}
6683
6684NamespaceDecl *Sema::getStdNamespace() const {
6685 return cast_or_null<NamespaceDecl>(
6686 StdNamespace.get(Context.getExternalSource()));
6687}
6688
Douglas Gregorcdf87022010-06-29 17:53:46 +00006689/// \brief Retrieve the special "std" namespace, which may require us to
6690/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006691NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006692 if (!StdNamespace) {
6693 // The "std" namespace has not yet been defined, so build one implicitly.
6694 StdNamespace = NamespaceDecl::Create(Context,
6695 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006696 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006697 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006698 &PP.getIdentifierTable().get("std"),
6699 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006700 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006701 }
6702
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006703 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006704}
6705
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006706bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006707 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006708 "Looking for std::initializer_list outside of C++.");
6709
6710 // We're looking for implicit instantiations of
6711 // template <typename E> class std::initializer_list.
6712
6713 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6714 return false;
6715
Sebastian Redl43144e72012-01-17 22:49:58 +00006716 ClassTemplateDecl *Template = 0;
6717 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006718
Sebastian Redl43144e72012-01-17 22:49:58 +00006719 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006720
Sebastian Redl43144e72012-01-17 22:49:58 +00006721 ClassTemplateSpecializationDecl *Specialization =
6722 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6723 if (!Specialization)
6724 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006725
Sebastian Redl43144e72012-01-17 22:49:58 +00006726 Template = Specialization->getSpecializedTemplate();
6727 Arguments = Specialization->getTemplateArgs().data();
6728 } else if (const TemplateSpecializationType *TST =
6729 Ty->getAs<TemplateSpecializationType>()) {
6730 Template = dyn_cast_or_null<ClassTemplateDecl>(
6731 TST->getTemplateName().getAsTemplateDecl());
6732 Arguments = TST->getArgs();
6733 }
6734 if (!Template)
6735 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006736
6737 if (!StdInitializerList) {
6738 // Haven't recognized std::initializer_list yet, maybe this is it.
6739 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6740 if (TemplateClass->getIdentifier() !=
6741 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006742 !getStdNamespace()->InEnclosingNamespaceSetOf(
6743 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006744 return false;
6745 // This is a template called std::initializer_list, but is it the right
6746 // template?
6747 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006748 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006749 return false;
6750 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6751 return false;
6752
6753 // It's the right template.
6754 StdInitializerList = Template;
6755 }
6756
6757 if (Template != StdInitializerList)
6758 return false;
6759
6760 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006761 if (Element)
6762 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006763 return true;
6764}
6765
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006766static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6767 NamespaceDecl *Std = S.getStdNamespace();
6768 if (!Std) {
6769 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6770 return 0;
6771 }
6772
6773 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6774 Loc, Sema::LookupOrdinaryName);
6775 if (!S.LookupQualifiedName(Result, Std)) {
6776 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6777 return 0;
6778 }
6779 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6780 if (!Template) {
6781 Result.suppressDiagnostics();
6782 // We found something weird. Complain about the first thing we found.
6783 NamedDecl *Found = *Result.begin();
6784 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6785 return 0;
6786 }
6787
6788 // We found some template called std::initializer_list. Now verify that it's
6789 // correct.
6790 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006791 if (Params->getMinRequiredArguments() != 1 ||
6792 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006793 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6794 return 0;
6795 }
6796
6797 return Template;
6798}
6799
6800QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6801 if (!StdInitializerList) {
6802 StdInitializerList = LookupStdInitializerList(*this, Loc);
6803 if (!StdInitializerList)
6804 return QualType();
6805 }
6806
6807 TemplateArgumentListInfo Args(Loc, Loc);
6808 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6809 Context.getTrivialTypeSourceInfo(Element,
6810 Loc)));
6811 return Context.getCanonicalType(
6812 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6813}
6814
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006815bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6816 // C++ [dcl.init.list]p2:
6817 // A constructor is an initializer-list constructor if its first parameter
6818 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6819 // std::initializer_list<E> for some type E, and either there are no other
6820 // parameters or else all other parameters have default arguments.
6821 if (Ctor->getNumParams() < 1 ||
6822 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6823 return false;
6824
6825 QualType ArgType = Ctor->getParamDecl(0)->getType();
6826 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6827 ArgType = RT->getPointeeType().getUnqualifiedType();
6828
6829 return isStdInitializerList(ArgType, 0);
6830}
6831
Douglas Gregora172e082011-03-26 22:25:30 +00006832/// \brief Determine whether a using statement is in a context where it will be
6833/// apply in all contexts.
6834static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6835 switch (CurContext->getDeclKind()) {
6836 case Decl::TranslationUnit:
6837 return true;
6838 case Decl::LinkageSpec:
6839 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6840 default:
6841 return false;
6842 }
6843}
6844
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006845namespace {
6846
6847// Callback to only accept typo corrections that are namespaces.
6848class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006849public:
6850 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6851 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006852 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006853 return false;
6854 }
6855};
6856
6857}
6858
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006859static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6860 CXXScopeSpec &SS,
6861 SourceLocation IdentLoc,
6862 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006863 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006864 R.clear();
6865 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006866 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006867 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006868 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006869 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6870 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006871 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006872 S.diagnoseTypo(Corrected,
6873 S.PDiag(diag::err_using_directive_member_suggest)
6874 << Ident << DC << DroppedSpecifier << SS.getRange(),
6875 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006876 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006877 S.diagnoseTypo(Corrected,
6878 S.PDiag(diag::err_using_directive_suggest) << Ident,
6879 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006880 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006881 R.addDecl(Corrected.getCorrectionDecl());
6882 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006883 }
6884 return false;
6885}
6886
John McCall48871652010-08-21 09:40:31 +00006887Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006888 SourceLocation UsingLoc,
6889 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006890 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006891 SourceLocation IdentLoc,
6892 IdentifierInfo *NamespcName,
6893 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006894 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6895 assert(NamespcName && "Invalid NamespcName.");
6896 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006897
6898 // This can only happen along a recovery path.
6899 while (S->getFlags() & Scope::TemplateParamScope)
6900 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006901 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006902
Douglas Gregor889ceb72009-02-03 19:21:40 +00006903 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006904 NestedNameSpecifier *Qualifier = 0;
6905 if (SS.isSet())
6906 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6907
Douglas Gregor34074322009-01-14 22:20:51 +00006908 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006909 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6910 LookupParsedName(R, S, &SS);
6911 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006912 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006913
Douglas Gregorcdf87022010-06-29 17:53:46 +00006914 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006915 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006916 // Allow "using namespace std;" or "using namespace ::std;" even if
6917 // "std" hasn't been defined yet, for GCC compatibility.
6918 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6919 NamespcName->isStr("std")) {
6920 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006921 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006922 R.resolveKind();
6923 }
6924 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006925 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006926 }
6927
John McCall9f3059a2009-10-09 21:13:30 +00006928 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006929 NamedDecl *Named = R.getFoundDecl();
6930 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6931 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006932 // C++ [namespace.udir]p1:
6933 // A using-directive specifies that the names in the nominated
6934 // namespace can be used in the scope in which the
6935 // using-directive appears after the using-directive. During
6936 // unqualified name lookup (3.4.1), the names appear as if they
6937 // were declared in the nearest enclosing namespace which
6938 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006939 // namespace. [Note: in this context, "contains" means "contains
6940 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006941
6942 // Find enclosing context containing both using-directive and
6943 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006944 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006945 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6946 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6947 CommonAncestor = CommonAncestor->getParent();
6948
Sebastian Redla6602e92009-11-23 15:34:23 +00006949 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006950 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006951 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006952
Douglas Gregora172e082011-03-26 22:25:30 +00006953 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006954 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006955 Diag(IdentLoc, diag::warn_using_directive_in_header);
6956 }
6957
Douglas Gregor889ceb72009-02-03 19:21:40 +00006958 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006959 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006960 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006961 }
6962
Richard Smith54ecd982013-02-20 19:22:51 +00006963 if (UDir)
6964 ProcessDeclAttributeList(S, UDir, AttrList);
6965
John McCall48871652010-08-21 09:40:31 +00006966 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006967}
6968
6969void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006970 // If the scope has an associated entity and the using directive is at
6971 // namespace or translation unit scope, add the UsingDirectiveDecl into
6972 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006973 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00006974 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006975 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006976 else
Richard Smith05afe5e2012-03-13 03:12:56 +00006977 // Otherwise, it is at block sope. The using-directives will affect lookup
6978 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00006979 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006980}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006981
Douglas Gregorfec52632009-06-20 00:51:54 +00006982
John McCall48871652010-08-21 09:40:31 +00006983Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006984 AccessSpecifier AS,
6985 bool HasUsingKeyword,
6986 SourceLocation UsingLoc,
6987 CXXScopeSpec &SS,
6988 UnqualifiedId &Name,
6989 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00006990 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00006991 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006992 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006993
Douglas Gregor220f4272009-11-04 16:30:06 +00006994 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006995 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006996 case UnqualifiedId::IK_Identifier:
6997 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006998 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006999 case UnqualifiedId::IK_ConversionFunctionId:
7000 break;
7001
7002 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007003 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007004 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007005 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007006 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007007 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007008 diag::err_using_decl_constructor)
7009 << SS.getRange();
7010
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007011 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007012
John McCall48871652010-08-21 09:40:31 +00007013 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007014
7015 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007016 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007017 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007018 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007019
7020 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007021 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007022 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007023 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007024 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007025
7026 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7027 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007028 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007029 return 0;
John McCall3969e302009-12-08 07:46:18 +00007030
Richard Smithc2bc61b2013-03-18 21:12:30 +00007031 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007032 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007033 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007034 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7035 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007036 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007037 }
7038
Douglas Gregorc4356532010-12-16 00:46:58 +00007039 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7040 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7041 return 0;
7042
John McCall3f746822009-11-17 05:59:44 +00007043 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007044 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007045 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007046 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007047 if (UD)
7048 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007049
John McCall48871652010-08-21 09:40:31 +00007050 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007051}
7052
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007053/// \brief Determine whether a using declaration considers the given
7054/// declarations as "equivalent", e.g., if they are redeclarations of
7055/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007056static bool
7057IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7058 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007059 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007060
Richard Smithdda56e42011-04-15 14:24:37 +00007061 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007062 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007063 return Context.hasSameType(TD1->getUnderlyingType(),
7064 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007065
7066 return false;
7067}
7068
7069
John McCall84d87672009-12-10 09:41:52 +00007070/// Determines whether to create a using shadow decl for a particular
7071/// decl, given the set of decls existing prior to this using lookup.
7072bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007073 const LookupResult &Previous,
7074 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007075 // Diagnose finding a decl which is not from a base class of the
7076 // current class. We do this now because there are cases where this
7077 // function will silently decide not to build a shadow decl, which
7078 // will pre-empt further diagnostics.
7079 //
7080 // We don't need to do this in C++0x because we do the check once on
7081 // the qualifier.
7082 //
7083 // FIXME: diagnose the following if we care enough:
7084 // struct A { int foo; };
7085 // struct B : A { using A::foo; };
7086 // template <class T> struct C : A {};
7087 // template <class T> struct D : C<T> { using B::foo; } // <---
7088 // This is invalid (during instantiation) in C++03 because B::foo
7089 // resolves to the using decl in B, which is not a base class of D<T>.
7090 // We can't diagnose it immediately because C<T> is an unknown
7091 // specialization. The UsingShadowDecl in D<T> then points directly
7092 // to A::foo, which will look well-formed when we instantiate.
7093 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007094 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007095 DeclContext *OrigDC = Orig->getDeclContext();
7096
7097 // Handle enums and anonymous structs.
7098 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7099 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7100 while (OrigRec->isAnonymousStructOrUnion())
7101 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7102
7103 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7104 if (OrigDC == CurContext) {
7105 Diag(Using->getLocation(),
7106 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007107 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007108 Diag(Orig->getLocation(), diag::note_using_decl_target);
7109 return true;
7110 }
7111
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007112 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007113 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007114 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007115 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007116 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007117 Diag(Orig->getLocation(), diag::note_using_decl_target);
7118 return true;
7119 }
7120 }
7121
7122 if (Previous.empty()) return false;
7123
7124 NamedDecl *Target = Orig;
7125 if (isa<UsingShadowDecl>(Target))
7126 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7127
John McCalla17e83e2009-12-11 02:33:26 +00007128 // If the target happens to be one of the previous declarations, we
7129 // don't have a conflict.
7130 //
7131 // FIXME: but we might be increasing its access, in which case we
7132 // should redeclare it.
7133 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007134 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007135 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7136 I != E; ++I) {
7137 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007138 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7139 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7140 PrevShadow = Shadow;
7141 FoundEquivalentDecl = true;
7142 }
John McCalla17e83e2009-12-11 02:33:26 +00007143
7144 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7145 }
7146
Richard Smithfd8634a2013-10-23 02:17:46 +00007147 if (FoundEquivalentDecl)
7148 return false;
7149
John McCall84d87672009-12-10 09:41:52 +00007150 if (Target->isFunctionOrFunctionTemplate()) {
7151 FunctionDecl *FD;
7152 if (isa<FunctionTemplateDecl>(Target))
7153 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7154 else
7155 FD = cast<FunctionDecl>(Target);
7156
7157 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007158 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007159 case Ovl_Overload:
7160 return false;
7161
7162 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007163 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007164 break;
7165
7166 // We found a decl with the exact signature.
7167 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007168 // If we're in a record, we want to hide the target, so we
7169 // return true (without a diagnostic) to tell the caller not to
7170 // build a shadow decl.
7171 if (CurContext->isRecord())
7172 return true;
7173
7174 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007175 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007176 break;
7177 }
7178
7179 Diag(Target->getLocation(), diag::note_using_decl_target);
7180 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7181 return true;
7182 }
7183
7184 // Target is not a function.
7185
John McCall84d87672009-12-10 09:41:52 +00007186 if (isa<TagDecl>(Target)) {
7187 // No conflict between a tag and a non-tag.
7188 if (!Tag) return false;
7189
John McCalle29c5cd2009-12-10 19:51:03 +00007190 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007191 Diag(Target->getLocation(), diag::note_using_decl_target);
7192 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7193 return true;
7194 }
7195
7196 // No conflict between a tag and a non-tag.
7197 if (!NonTag) return false;
7198
John McCalle29c5cd2009-12-10 19:51:03 +00007199 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007200 Diag(Target->getLocation(), diag::note_using_decl_target);
7201 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7202 return true;
7203}
7204
John McCall3f746822009-11-17 05:59:44 +00007205/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007206UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007207 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007208 NamedDecl *Orig,
7209 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007210
7211 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007212 NamedDecl *Target = Orig;
7213 if (isa<UsingShadowDecl>(Target)) {
7214 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7215 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007216 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007217
John McCall3f746822009-11-17 05:59:44 +00007218 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007219 = UsingShadowDecl::Create(Context, CurContext,
7220 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007221 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007222
Douglas Gregor457104e2010-09-29 04:25:11 +00007223 Shadow->setAccess(UD->getAccess());
7224 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7225 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007226
7227 Shadow->setPreviousDecl(PrevDecl);
7228
John McCall3f746822009-11-17 05:59:44 +00007229 if (S)
John McCall3969e302009-12-08 07:46:18 +00007230 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007231 else
John McCall3969e302009-12-08 07:46:18 +00007232 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007233
John McCall3969e302009-12-08 07:46:18 +00007234
John McCall84d87672009-12-10 09:41:52 +00007235 return Shadow;
7236}
John McCall3969e302009-12-08 07:46:18 +00007237
John McCall84d87672009-12-10 09:41:52 +00007238/// Hides a using shadow declaration. This is required by the current
7239/// using-decl implementation when a resolvable using declaration in a
7240/// class is followed by a declaration which would hide or override
7241/// one or more of the using decl's targets; for example:
7242///
7243/// struct Base { void foo(int); };
7244/// struct Derived : Base {
7245/// using Base::foo;
7246/// void foo(int);
7247/// };
7248///
7249/// The governing language is C++03 [namespace.udecl]p12:
7250///
7251/// When a using-declaration brings names from a base class into a
7252/// derived class scope, member functions in the derived class
7253/// override and/or hide member functions with the same name and
7254/// parameter types in a base class (rather than conflicting).
7255///
7256/// There are two ways to implement this:
7257/// (1) optimistically create shadow decls when they're not hidden
7258/// by existing declarations, or
7259/// (2) don't create any shadow decls (or at least don't make them
7260/// visible) until we've fully parsed/instantiated the class.
7261/// The problem with (1) is that we might have to retroactively remove
7262/// a shadow decl, which requires several O(n) operations because the
7263/// decl structures are (very reasonably) not designed for removal.
7264/// (2) avoids this but is very fiddly and phase-dependent.
7265void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007266 if (Shadow->getDeclName().getNameKind() ==
7267 DeclarationName::CXXConversionFunctionName)
7268 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7269
John McCall84d87672009-12-10 09:41:52 +00007270 // Remove it from the DeclContext...
7271 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007272
John McCall84d87672009-12-10 09:41:52 +00007273 // ...and the scope, if applicable...
7274 if (S) {
John McCall48871652010-08-21 09:40:31 +00007275 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007276 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007277 }
7278
John McCall84d87672009-12-10 09:41:52 +00007279 // ...and the using decl.
7280 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7281
7282 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007283 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007284}
7285
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007286namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007287class UsingValidatorCCC : public CorrectionCandidateCallback {
7288public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007289 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7290 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007291 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007292 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007293
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007294 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7295 NamedDecl *ND = Candidate.getCorrectionDecl();
7296
7297 // Keywords are not valid here.
7298 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007299 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007300
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007301 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7302 !isa<TypeDecl>(ND))
7303 return false;
7304
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007305 // Completely unqualified names are invalid for a 'using' declaration.
7306 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7307 return false;
7308
7309 if (isa<TypeDecl>(ND))
7310 return HasTypenameKeyword || !IsInstantiation;
7311
7312 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007313 }
7314
7315private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007316 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007317 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007318 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007319};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007320} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007321
John McCalle61f2ba2009-11-18 02:36:19 +00007322/// Builds a using declaration.
7323///
7324/// \param IsInstantiation - Whether this call arises from an
7325/// instantiation of an unresolved using declaration. We treat
7326/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007327NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7328 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007329 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007330 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007331 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007332 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007333 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007334 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007335 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007336 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007337 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007338
Anders Carlssonf038fc22009-08-28 05:49:21 +00007339 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007340
Anders Carlsson59140b32009-08-28 03:16:11 +00007341 if (SS.isEmpty()) {
7342 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007343 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007344 }
Mike Stump11289f42009-09-09 15:08:12 +00007345
John McCall84d87672009-12-10 09:41:52 +00007346 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007347 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007348 ForRedeclaration);
7349 Previous.setHideTags(false);
7350 if (S) {
7351 LookupName(Previous, S);
7352
7353 // It is really dumb that we have to do this.
7354 LookupResult::Filter F = Previous.makeFilter();
7355 while (F.hasNext()) {
7356 NamedDecl *D = F.next();
7357 if (!isDeclInScope(D, CurContext, S))
7358 F.erase();
7359 }
7360 F.done();
7361 } else {
7362 assert(IsInstantiation && "no scope in non-instantiation");
7363 assert(CurContext->isRecord() && "scope not record in instantiation");
7364 LookupQualifiedName(Previous, CurContext);
7365 }
7366
John McCall84d87672009-12-10 09:41:52 +00007367 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007368 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7369 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007370 return 0;
7371
7372 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007373 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7374 return 0;
7375
John McCall84c16cf2009-11-12 03:15:40 +00007376 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007377 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007378 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007379 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007380 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007381 // FIXME: not all declaration name kinds are legal here
7382 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7383 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007384 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007385 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007386 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007387 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7388 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007389 }
John McCallb96ec562009-12-04 22:46:56 +00007390 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007391 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007392 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007393 }
John McCallb96ec562009-12-04 22:46:56 +00007394 D->setAccess(AS);
7395 CurContext->addDecl(D);
7396
7397 if (!LookupContext) return D;
7398 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007399
John McCall0b66eb32010-05-01 00:40:08 +00007400 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007401 UD->setInvalidDecl();
7402 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007403 }
7404
Richard Smith23d55872012-04-02 01:30:27 +00007405 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007406 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007407 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007408 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007409 return UD;
7410 }
7411
7412 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007413
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007414 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007415
John McCall3969e302009-12-08 07:46:18 +00007416 // Unlike most lookups, we don't always want to hide tag
7417 // declarations: tag names are visible through the using declaration
7418 // even if hidden by ordinary names, *except* in a dependent context
7419 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007420 if (!IsInstantiation)
7421 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007422
John McCall5dadb652012-04-07 03:04:20 +00007423 // For the purposes of this lookup, we have a base object type
7424 // equal to that of the current context.
7425 if (CurContext->isRecord()) {
7426 R.setBaseObjectType(
7427 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7428 }
7429
John McCall27b18f82009-11-17 02:14:36 +00007430 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007431
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007432 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007433 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007434 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7435 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007436 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7437 R.getLookupKind(), S, &SS, CCC)){
7438 // We reject any correction for which ND would be NULL.
7439 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007440 R.setLookupName(Corrected.getCorrection());
7441 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007442 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007443 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007444 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7445 << NameInfo.getName() << LookupContext << 0
7446 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007447 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007448 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007449 << NameInfo.getName() << LookupContext << SS.getRange();
7450 UD->setInvalidDecl();
7451 return UD;
7452 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007453 }
7454
John McCallb96ec562009-12-04 22:46:56 +00007455 if (R.isAmbiguous()) {
7456 UD->setInvalidDecl();
7457 return UD;
7458 }
Mike Stump11289f42009-09-09 15:08:12 +00007459
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007460 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007461 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007462 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007463 Diag(IdentLoc, diag::err_using_typename_non_type);
7464 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7465 Diag((*I)->getUnderlyingDecl()->getLocation(),
7466 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007467 UD->setInvalidDecl();
7468 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007469 }
7470 } else {
7471 // If we asked for a non-typename and we got a type, error out,
7472 // but only if this is an instantiation of an unresolved using
7473 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007474 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007475 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7476 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007477 UD->setInvalidDecl();
7478 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007479 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007480 }
7481
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007482 // C++0x N2914 [namespace.udecl]p6:
7483 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007484 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007485 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7486 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007487 UD->setInvalidDecl();
7488 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007489 }
Mike Stump11289f42009-09-09 15:08:12 +00007490
John McCall84d87672009-12-10 09:41:52 +00007491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007492 UsingShadowDecl *PrevDecl = 0;
7493 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7494 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007495 }
John McCall3f746822009-11-17 05:59:44 +00007496
7497 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007498}
7499
Sebastian Redl08905022011-02-05 19:23:19 +00007500/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007501bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007502 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007503
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007504 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007505 assert(SourceType &&
7506 "Using decl naming constructor doesn't have type in scope spec.");
7507 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7508
7509 // Check whether the named type is a direct base class.
7510 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7511 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7512 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7513 BaseIt != BaseE; ++BaseIt) {
7514 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7515 if (CanonicalSourceType == BaseType)
7516 break;
Richard Smith23d55872012-04-02 01:30:27 +00007517 if (BaseIt->getType()->isDependentType())
7518 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007519 }
7520
7521 if (BaseIt == BaseE) {
7522 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007523 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007524 diag::err_using_decl_constructor_not_in_direct_base)
7525 << UD->getNameInfo().getSourceRange()
7526 << QualType(SourceType, 0) << TargetClass;
7527 return true;
7528 }
7529
Richard Smith23d55872012-04-02 01:30:27 +00007530 if (!CurContext->isDependentContext())
7531 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007532
7533 return false;
7534}
7535
John McCall84d87672009-12-10 09:41:52 +00007536/// Checks that the given using declaration is not an invalid
7537/// redeclaration. Note that this is checking only for the using decl
7538/// itself, not for any ill-formedness among the UsingShadowDecls.
7539bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007540 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007541 const CXXScopeSpec &SS,
7542 SourceLocation NameLoc,
7543 const LookupResult &Prev) {
7544 // C++03 [namespace.udecl]p8:
7545 // C++0x [namespace.udecl]p10:
7546 // A using-declaration is a declaration and can therefore be used
7547 // repeatedly where (and only where) multiple declarations are
7548 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007549 //
John McCall032092f2010-11-29 18:01:58 +00007550 // That's in non-member contexts.
7551 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007552 return false;
7553
7554 NestedNameSpecifier *Qual
7555 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7556
7557 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7558 NamedDecl *D = *I;
7559
7560 bool DTypename;
7561 NestedNameSpecifier *DQual;
7562 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007563 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007564 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007565 } else if (UnresolvedUsingValueDecl *UD
7566 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7567 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007568 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007569 } else if (UnresolvedUsingTypenameDecl *UD
7570 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7571 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007572 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007573 } else continue;
7574
7575 // using decls differ if one says 'typename' and the other doesn't.
7576 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007577 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007578
7579 // using decls differ if they name different scopes (but note that
7580 // template instantiation can cause this check to trigger when it
7581 // didn't before instantiation).
7582 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7583 Context.getCanonicalNestedNameSpecifier(DQual))
7584 continue;
7585
7586 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007587 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007588 return true;
7589 }
7590
7591 return false;
7592}
7593
John McCall3969e302009-12-08 07:46:18 +00007594
John McCallb96ec562009-12-04 22:46:56 +00007595/// Checks that the given nested-name qualifier used in a using decl
7596/// in the current context is appropriately related to the current
7597/// scope. If an error is found, diagnoses it and returns true.
7598bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7599 const CXXScopeSpec &SS,
7600 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007601 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007602
John McCall3969e302009-12-08 07:46:18 +00007603 if (!CurContext->isRecord()) {
7604 // C++03 [namespace.udecl]p3:
7605 // C++0x [namespace.udecl]p8:
7606 // A using-declaration for a class member shall be a member-declaration.
7607
7608 // If we weren't able to compute a valid scope, it must be a
7609 // dependent class scope.
7610 if (!NamedContext || NamedContext->isRecord()) {
7611 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7612 << SS.getRange();
7613 return true;
7614 }
7615
7616 // Otherwise, everything is known to be fine.
7617 return false;
7618 }
7619
7620 // The current scope is a record.
7621
7622 // If the named context is dependent, we can't decide much.
7623 if (!NamedContext) {
7624 // FIXME: in C++0x, we can diagnose if we can prove that the
7625 // nested-name-specifier does not refer to a base class, which is
7626 // still possible in some cases.
7627
7628 // Otherwise we have to conservatively report that things might be
7629 // okay.
7630 return false;
7631 }
7632
7633 if (!NamedContext->isRecord()) {
7634 // Ideally this would point at the last name in the specifier,
7635 // but we don't have that level of source info.
7636 Diag(SS.getRange().getBegin(),
7637 diag::err_using_decl_nested_name_specifier_is_not_class)
7638 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7639 return true;
7640 }
7641
Douglas Gregor7c842292010-12-21 07:41:49 +00007642 if (!NamedContext->isDependentContext() &&
7643 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7644 return true;
7645
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007646 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007647 // C++0x [namespace.udecl]p3:
7648 // In a using-declaration used as a member-declaration, the
7649 // nested-name-specifier shall name a base class of the class
7650 // being defined.
7651
7652 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7653 cast<CXXRecordDecl>(NamedContext))) {
7654 if (CurContext == NamedContext) {
7655 Diag(NameLoc,
7656 diag::err_using_decl_nested_name_specifier_is_current_class)
7657 << SS.getRange();
7658 return true;
7659 }
7660
7661 Diag(SS.getRange().getBegin(),
7662 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7663 << (NestedNameSpecifier*) SS.getScopeRep()
7664 << cast<CXXRecordDecl>(CurContext)
7665 << SS.getRange();
7666 return true;
7667 }
7668
7669 return false;
7670 }
7671
7672 // C++03 [namespace.udecl]p4:
7673 // A using-declaration used as a member-declaration shall refer
7674 // to a member of a base class of the class being defined [etc.].
7675
7676 // Salient point: SS doesn't have to name a base class as long as
7677 // lookup only finds members from base classes. Therefore we can
7678 // diagnose here only if we can prove that that can't happen,
7679 // i.e. if the class hierarchies provably don't intersect.
7680
7681 // TODO: it would be nice if "definitely valid" results were cached
7682 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7683 // need to be repeated.
7684
7685 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007686 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007687
7688 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7689 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7690 Data->Bases.insert(Base);
7691 return true;
7692 }
7693
7694 bool hasDependentBases(const CXXRecordDecl *Class) {
7695 return !Class->forallBases(collect, this);
7696 }
7697
7698 /// Returns true if the base is dependent or is one of the
7699 /// accumulated base classes.
7700 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7701 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7702 return !Data->Bases.count(Base);
7703 }
7704
7705 bool mightShareBases(const CXXRecordDecl *Class) {
7706 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7707 }
7708 };
7709
7710 UserData Data;
7711
7712 // Returns false if we find a dependent base.
7713 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7714 return false;
7715
7716 // Returns false if the class has a dependent base or if it or one
7717 // of its bases is present in the base set of the current context.
7718 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7719 return false;
7720
7721 Diag(SS.getRange().getBegin(),
7722 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7723 << (NestedNameSpecifier*) SS.getScopeRep()
7724 << cast<CXXRecordDecl>(CurContext)
7725 << SS.getRange();
7726
7727 return true;
John McCallb96ec562009-12-04 22:46:56 +00007728}
7729
Richard Smithdda56e42011-04-15 14:24:37 +00007730Decl *Sema::ActOnAliasDeclaration(Scope *S,
7731 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007732 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007733 SourceLocation UsingLoc,
7734 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007735 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007736 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007737 // Skip up to the relevant declaration scope.
7738 while (S->getFlags() & Scope::TemplateParamScope)
7739 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007740 assert((S->getFlags() & Scope::DeclScope) &&
7741 "got alias-declaration outside of declaration scope");
7742
7743 if (Type.isInvalid())
7744 return 0;
7745
7746 bool Invalid = false;
7747 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7748 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007749 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007750
7751 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7752 return 0;
7753
7754 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007755 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007756 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007757 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7758 TInfo->getTypeLoc().getBeginLoc());
7759 }
Richard Smithdda56e42011-04-15 14:24:37 +00007760
7761 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7762 LookupName(Previous, S);
7763
7764 // Warn about shadowing the name of a template parameter.
7765 if (Previous.isSingleResult() &&
7766 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007767 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007768 Previous.clear();
7769 }
7770
7771 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7772 "name in alias declaration must be an identifier");
7773 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7774 Name.StartLocation,
7775 Name.Identifier, TInfo);
7776
7777 NewTD->setAccess(AS);
7778
7779 if (Invalid)
7780 NewTD->setInvalidDecl();
7781
Richard Smith54ecd982013-02-20 19:22:51 +00007782 ProcessDeclAttributeList(S, NewTD, AttrList);
7783
Richard Smith3f1b5d02011-05-05 21:57:07 +00007784 CheckTypedefForVariablyModifiedType(S, NewTD);
7785 Invalid |= NewTD->isInvalidDecl();
7786
Richard Smithdda56e42011-04-15 14:24:37 +00007787 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007788
7789 NamedDecl *NewND;
7790 if (TemplateParamLists.size()) {
7791 TypeAliasTemplateDecl *OldDecl = 0;
7792 TemplateParameterList *OldTemplateParams = 0;
7793
7794 if (TemplateParamLists.size() != 1) {
7795 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007796 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7797 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007798 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007799 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007800
7801 // Only consider previous declarations in the same scope.
7802 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7803 /*ExplicitInstantiationOrSpecialization*/false);
7804 if (!Previous.empty()) {
7805 Redeclaration = true;
7806
7807 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7808 if (!OldDecl && !Invalid) {
7809 Diag(UsingLoc, diag::err_redefinition_different_kind)
7810 << Name.Identifier;
7811
7812 NamedDecl *OldD = Previous.getRepresentativeDecl();
7813 if (OldD->getLocation().isValid())
7814 Diag(OldD->getLocation(), diag::note_previous_definition);
7815
7816 Invalid = true;
7817 }
7818
7819 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7820 if (TemplateParameterListsAreEqual(TemplateParams,
7821 OldDecl->getTemplateParameters(),
7822 /*Complain=*/true,
7823 TPL_TemplateMatch))
7824 OldTemplateParams = OldDecl->getTemplateParameters();
7825 else
7826 Invalid = true;
7827
7828 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7829 if (!Invalid &&
7830 !Context.hasSameType(OldTD->getUnderlyingType(),
7831 NewTD->getUnderlyingType())) {
7832 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7833 // but we can't reasonably accept it.
7834 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7835 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7836 if (OldTD->getLocation().isValid())
7837 Diag(OldTD->getLocation(), diag::note_previous_definition);
7838 Invalid = true;
7839 }
7840 }
7841 }
7842
7843 // Merge any previous default template arguments into our parameters,
7844 // and check the parameter list.
7845 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7846 TPC_TypeAliasTemplate))
7847 return 0;
7848
7849 TypeAliasTemplateDecl *NewDecl =
7850 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7851 Name.Identifier, TemplateParams,
7852 NewTD);
7853
7854 NewDecl->setAccess(AS);
7855
7856 if (Invalid)
7857 NewDecl->setInvalidDecl();
7858 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007859 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007860
7861 NewND = NewDecl;
7862 } else {
7863 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7864 NewND = NewTD;
7865 }
Richard Smithdda56e42011-04-15 14:24:37 +00007866
7867 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007868 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007869
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007870 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007871 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007872}
7873
John McCall48871652010-08-21 09:40:31 +00007874Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007875 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007876 SourceLocation AliasLoc,
7877 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007878 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007879 SourceLocation IdentLoc,
7880 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007881
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007882 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007883 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7884 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007885
Anders Carlssondca83c42009-03-28 06:23:46 +00007886 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007887 NamedDecl *PrevDecl
7888 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7889 ForRedeclaration);
7890 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7891 PrevDecl = 0;
7892
7893 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007894 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007895 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007896 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007897 // FIXME: At some point, we'll want to create the (redundant)
7898 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007899 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007900 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007901 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007902 }
Mike Stump11289f42009-09-09 15:08:12 +00007903
Anders Carlssondca83c42009-03-28 06:23:46 +00007904 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7905 diag::err_redefinition_different_kind;
7906 Diag(AliasLoc, DiagID) << Alias;
7907 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007908 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007909 }
7910
John McCall27b18f82009-11-17 02:14:36 +00007911 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007912 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007913
John McCall9f3059a2009-10-09 21:13:30 +00007914 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007915 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007916 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007917 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007918 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007919 }
Mike Stump11289f42009-09-09 15:08:12 +00007920
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007921 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007922 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007923 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007924 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007925
John McCalld8d0d432010-02-16 06:53:13 +00007926 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007927 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007928}
7929
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007930Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007931Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7932 CXXMethodDecl *MD) {
7933 CXXRecordDecl *ClassDecl = MD->getParent();
7934
Douglas Gregor6d880b12010-07-01 22:31:05 +00007935 // C++ [except.spec]p14:
7936 // An implicitly declared special member function (Clause 12) shall have an
7937 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007938 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007939 if (ClassDecl->isInvalidDecl())
7940 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007941
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007942 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007943 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7944 BEnd = ClassDecl->bases_end();
7945 B != BEnd; ++B) {
7946 if (B->isVirtual()) // Handled below.
7947 continue;
7948
Douglas Gregor9672f922010-07-03 00:47:00 +00007949 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7950 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007951 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7952 // If this is a deleted function, add it anyway. This might be conformant
7953 // with the standard. This might not. I'm not sure. It might not matter.
7954 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007955 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007956 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007957 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007958
7959 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007960 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7961 BEnd = ClassDecl->vbases_end();
7962 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007963 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7964 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007965 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7966 // If this is a deleted function, add it anyway. This might be conformant
7967 // with the standard. This might not. I'm not sure. It might not matter.
7968 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007969 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007970 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007971 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007972
7973 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007974 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7975 FEnd = ClassDecl->field_end();
7976 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007977 if (F->hasInClassInitializer()) {
7978 if (Expr *E = F->getInClassInitializer())
7979 ExceptSpec.CalledExpr(E);
7980 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00007981 // DR1351:
7982 // If the brace-or-equal-initializer of a non-static data member
7983 // invokes a defaulted default constructor of its class or of an
7984 // enclosing class in a potentially evaluated subexpression, the
7985 // program is ill-formed.
7986 //
7987 // This resolution is unworkable: the exception specification of the
7988 // default constructor can be needed in an unevaluated context, in
7989 // particular, in the operand of a noexcept-expression, and we can be
7990 // unable to compute an exception specification for an enclosed class.
7991 //
7992 // We do not allow an in-class initializer to require the evaluation
7993 // of the exception specification for any in-class initializer whose
7994 // definition is not lexically complete.
7995 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00007996 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007997 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007998 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7999 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8000 // If this is a deleted function, add it anyway. This might be conformant
8001 // with the standard. This might not. I'm not sure. It might not matter.
8002 // In particular, the problem is that this function never gets called. It
8003 // might just be ill-formed because this function attempts to refer to
8004 // a deleted function here.
8005 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008006 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008007 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008008 }
John McCalldb40c7f2010-12-14 08:05:40 +00008009
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008010 return ExceptSpec;
8011}
8012
Richard Smithc2bc61b2013-03-18 21:12:30 +00008013Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008014Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8015 CXXRecordDecl *ClassDecl = CD->getParent();
8016
8017 // C++ [except.spec]p14:
8018 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008019 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008020 if (ClassDecl->isInvalidDecl())
8021 return ExceptSpec;
8022
8023 // Inherited constructor.
8024 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8025 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8026 // FIXME: Copying or moving the parameters could add extra exceptions to the
8027 // set, as could the default arguments for the inherited constructor. This
8028 // will be addressed when we implement the resolution of core issue 1351.
8029 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8030
8031 // Direct base-class constructors.
8032 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8033 BEnd = ClassDecl->bases_end();
8034 B != BEnd; ++B) {
8035 if (B->isVirtual()) // Handled below.
8036 continue;
8037
8038 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8039 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8040 if (BaseClassDecl == InheritedDecl)
8041 continue;
8042 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8043 if (Constructor)
8044 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8045 }
8046 }
8047
8048 // Virtual base-class constructors.
8049 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8050 BEnd = ClassDecl->vbases_end();
8051 B != BEnd; ++B) {
8052 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8053 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8054 if (BaseClassDecl == InheritedDecl)
8055 continue;
8056 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8057 if (Constructor)
8058 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8059 }
8060 }
8061
8062 // Field constructors.
8063 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8064 FEnd = ClassDecl->field_end();
8065 F != FEnd; ++F) {
8066 if (F->hasInClassInitializer()) {
8067 if (Expr *E = F->getInClassInitializer())
8068 ExceptSpec.CalledExpr(E);
8069 else if (!F->isInvalidDecl())
8070 Diag(CD->getLocation(),
8071 diag::err_in_class_initializer_references_def_ctor) << CD;
8072 } else if (const RecordType *RecordTy
8073 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8074 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8075 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8076 if (Constructor)
8077 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8078 }
8079 }
8080
Richard Smithc2bc61b2013-03-18 21:12:30 +00008081 return ExceptSpec;
8082}
8083
Richard Smith8bf22e52012-11-29 01:34:07 +00008084namespace {
8085/// RAII object to register a special member as being currently declared.
8086struct DeclaringSpecialMember {
8087 Sema &S;
8088 Sema::SpecialMemberDecl D;
8089 bool WasAlreadyBeingDeclared;
8090
8091 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8092 : S(S), D(RD, CSM) {
8093 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8094 if (WasAlreadyBeingDeclared)
8095 // This almost never happens, but if it does, ensure that our cache
8096 // doesn't contain a stale result.
8097 S.SpecialMemberCache.clear();
8098
8099 // FIXME: Register a note to be produced if we encounter an error while
8100 // declaring the special member.
8101 }
8102 ~DeclaringSpecialMember() {
8103 if (!WasAlreadyBeingDeclared)
8104 S.SpecialMembersBeingDeclared.erase(D);
8105 }
8106
8107 /// \brief Are we already trying to declare this special member?
8108 bool isAlreadyBeingDeclared() const {
8109 return WasAlreadyBeingDeclared;
8110 }
8111};
8112}
8113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008114CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8115 CXXRecordDecl *ClassDecl) {
8116 // C++ [class.ctor]p5:
8117 // A default constructor for a class X is a constructor of class X
8118 // that can be called without an argument. If there is no
8119 // user-declared constructor for class X, a default constructor is
8120 // implicitly declared. An implicitly-declared default constructor
8121 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008122 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008123 "Should not build implicit default constructor!");
8124
Richard Smith8bf22e52012-11-29 01:34:07 +00008125 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8126 if (DSM.isAlreadyBeingDeclared())
8127 return 0;
8128
Richard Smithb5800092012-06-10 05:43:50 +00008129 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8130 CXXDefaultConstructor,
8131 false);
8132
Douglas Gregor6d880b12010-07-01 22:31:05 +00008133 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008134 CanQualType ClassType
8135 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008136 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008137 DeclarationName Name
8138 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008139 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008140 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008141 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008142 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008143 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008144 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008145 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008146 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008147
8148 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008149 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008150 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008151
Richard Smith6b02d462012-12-08 08:32:28 +00008152 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8153 // constructors is easy to compute.
8154 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8155
8156 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008157 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008158
Douglas Gregor9672f922010-07-03 00:47:00 +00008159 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008160 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008161
Douglas Gregor0be31a22010-07-02 17:43:08 +00008162 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008163 PushOnScopeChains(DefaultCon, S, false);
8164 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008165
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008166 return DefaultCon;
8167}
8168
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008169void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8170 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008171 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008172 !Constructor->doesThisDeclarationHaveABody() &&
8173 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008174 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008175
Anders Carlsson423f5d82010-04-23 16:04:08 +00008176 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008177 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008178
Eli Friedmaneaf34142012-10-18 20:14:08 +00008179 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008180 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008181 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008182 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008183 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008184 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008185 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008186 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008187 }
Douglas Gregor73193272010-09-20 16:48:21 +00008188
8189 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008190 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008191
Eli Friedman276dd182013-09-05 00:02:25 +00008192 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008193 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008194
8195 if (ASTMutationListener *L = getASTMutationListener()) {
8196 L->CompletedImplicitDefinition(Constructor);
8197 }
Richard Trieuef64e942013-10-25 00:56:00 +00008198
8199 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008200}
8201
Richard Smith938f40b2011-06-11 17:19:42 +00008202void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008203 // Perform any delayed checks on exception specifications.
8204 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008205}
8206
Richard Smith185be182013-04-10 05:48:59 +00008207namespace {
8208/// Information on inheriting constructors to declare.
8209class InheritingConstructorInfo {
8210public:
8211 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8212 : SemaRef(SemaRef), Derived(Derived) {
8213 // Mark the constructors that we already have in the derived class.
8214 //
8215 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8216 // unless there is a user-declared constructor with the same signature in
8217 // the class where the using-declaration appears.
8218 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8219 }
8220
8221 void inheritAll(CXXRecordDecl *RD) {
8222 visitAll(RD, &InheritingConstructorInfo::inherit);
8223 }
8224
8225private:
8226 /// Information about an inheriting constructor.
8227 struct InheritingConstructor {
8228 InheritingConstructor()
8229 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8230
8231 /// If \c true, a constructor with this signature is already declared
8232 /// in the derived class.
8233 bool DeclaredInDerived;
8234
8235 /// The constructor which is inherited.
8236 const CXXConstructorDecl *BaseCtor;
8237
8238 /// The derived constructor we declared.
8239 CXXConstructorDecl *DerivedCtor;
8240 };
8241
8242 /// Inheriting constructors with a given canonical type. There can be at
8243 /// most one such non-template constructor, and any number of templated
8244 /// constructors.
8245 struct InheritingConstructorsForType {
8246 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008247 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8248 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008249
8250 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8251 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8252 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8253 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8254 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8255 false, S.TPL_TemplateMatch))
8256 return Templates[I].second;
8257 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8258 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008259 }
Richard Smith185be182013-04-10 05:48:59 +00008260
8261 return NonTemplate;
8262 }
8263 };
8264
8265 /// Get or create the inheriting constructor record for a constructor.
8266 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8267 QualType CtorType) {
8268 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8269 .getEntry(SemaRef, Ctor);
8270 }
8271
8272 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8273
8274 /// Process all constructors for a class.
8275 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8276 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8277 CtorE = RD->ctor_end();
8278 CtorIt != CtorE; ++CtorIt)
8279 (this->*Callback)(*CtorIt);
8280 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8281 I(RD->decls_begin()), E(RD->decls_end());
8282 I != E; ++I) {
8283 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8284 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8285 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008286 }
8287 }
Richard Smith185be182013-04-10 05:48:59 +00008288
8289 /// Note that a constructor (or constructor template) was declared in Derived.
8290 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8291 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8292 }
8293
8294 /// Inherit a single constructor.
8295 void inherit(const CXXConstructorDecl *Ctor) {
8296 const FunctionProtoType *CtorType =
8297 Ctor->getType()->castAs<FunctionProtoType>();
8298 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8299 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8300
8301 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8302
8303 // Core issue (no number yet): the ellipsis is always discarded.
8304 if (EPI.Variadic) {
8305 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8306 SemaRef.Diag(Ctor->getLocation(),
8307 diag::note_using_decl_constructor_ellipsis);
8308 EPI.Variadic = false;
8309 }
8310
8311 // Declare a constructor for each number of parameters.
8312 //
8313 // C++11 [class.inhctor]p1:
8314 // The candidate set of inherited constructors from the class X named in
8315 // the using-declaration consists of [... modulo defects ...] for each
8316 // constructor or constructor template of X, the set of constructors or
8317 // constructor templates that results from omitting any ellipsis parameter
8318 // specification and successively omitting parameters with a default
8319 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008320 unsigned MinParams = minParamsToInherit(Ctor);
8321 unsigned Params = Ctor->getNumParams();
8322 if (Params >= MinParams) {
8323 do
8324 declareCtor(UsingLoc, Ctor,
8325 SemaRef.Context.getFunctionType(
8326 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8327 while (Params > MinParams &&
8328 Ctor->getParamDecl(--Params)->hasDefaultArg());
8329 }
Richard Smith185be182013-04-10 05:48:59 +00008330 }
8331
8332 /// Find the using-declaration which specified that we should inherit the
8333 /// constructors of \p Base.
8334 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8335 // No fancy lookup required; just look for the base constructor name
8336 // directly within the derived class.
8337 ASTContext &Context = SemaRef.Context;
8338 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8339 Context.getCanonicalType(Context.getRecordType(Base)));
8340 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8341 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8342 }
8343
8344 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8345 // C++11 [class.inhctor]p3:
8346 // [F]or each constructor template in the candidate set of inherited
8347 // constructors, a constructor template is implicitly declared
8348 if (Ctor->getDescribedFunctionTemplate())
8349 return 0;
8350
8351 // For each non-template constructor in the candidate set of inherited
8352 // constructors other than a constructor having no parameters or a
8353 // copy/move constructor having a single parameter, a constructor is
8354 // implicitly declared [...]
8355 if (Ctor->getNumParams() == 0)
8356 return 1;
8357 if (Ctor->isCopyOrMoveConstructor())
8358 return 2;
8359
8360 // Per discussion on core reflector, never inherit a constructor which
8361 // would become a default, copy, or move constructor of Derived either.
8362 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8363 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8364 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8365 }
8366
8367 /// Declare a single inheriting constructor, inheriting the specified
8368 /// constructor, with the given type.
8369 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8370 QualType DerivedType) {
8371 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8372
8373 // C++11 [class.inhctor]p3:
8374 // ... a constructor is implicitly declared with the same constructor
8375 // characteristics unless there is a user-declared constructor with
8376 // the same signature in the class where the using-declaration appears
8377 if (Entry.DeclaredInDerived)
8378 return;
8379
8380 // C++11 [class.inhctor]p7:
8381 // If two using-declarations declare inheriting constructors with the
8382 // same signature, the program is ill-formed
8383 if (Entry.DerivedCtor) {
8384 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8385 // Only diagnose this once per constructor.
8386 if (Entry.DerivedCtor->isInvalidDecl())
8387 return;
8388 Entry.DerivedCtor->setInvalidDecl();
8389
8390 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8391 SemaRef.Diag(BaseCtor->getLocation(),
8392 diag::note_using_decl_constructor_conflict_current_ctor);
8393 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8394 diag::note_using_decl_constructor_conflict_previous_ctor);
8395 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8396 diag::note_using_decl_constructor_conflict_previous_using);
8397 } else {
8398 // Core issue (no number): if the same inheriting constructor is
8399 // produced by multiple base class constructors from the same base
8400 // class, the inheriting constructor is defined as deleted.
8401 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8402 }
8403
8404 return;
8405 }
8406
8407 ASTContext &Context = SemaRef.Context;
8408 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8409 Context.getCanonicalType(Context.getRecordType(Derived)));
8410 DeclarationNameInfo NameInfo(Name, UsingLoc);
8411
8412 TemplateParameterList *TemplateParams = 0;
8413 if (const FunctionTemplateDecl *FTD =
8414 BaseCtor->getDescribedFunctionTemplate()) {
8415 TemplateParams = FTD->getTemplateParameters();
8416 // We're reusing template parameters from a different DeclContext. This
8417 // is questionable at best, but works out because the template depth in
8418 // both places is guaranteed to be 0.
8419 // FIXME: Rebuild the template parameters in the new context, and
8420 // transform the function type to refer to them.
8421 }
8422
8423 // Build type source info pointing at the using-declaration. This is
8424 // required by template instantiation.
8425 TypeSourceInfo *TInfo =
8426 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8427 FunctionProtoTypeLoc ProtoLoc =
8428 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8429
8430 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8431 Context, Derived, UsingLoc, NameInfo, DerivedType,
8432 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8433 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8434
8435 // Build an unevaluated exception specification for this constructor.
8436 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8437 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8438 EPI.ExceptionSpecType = EST_Unevaluated;
8439 EPI.ExceptionSpecDecl = DerivedCtor;
8440 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8441 FPT->getArgTypes(), EPI));
8442
8443 // Build the parameter declarations.
8444 SmallVector<ParmVarDecl *, 16> ParamDecls;
8445 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8446 TypeSourceInfo *TInfo =
8447 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8448 ParmVarDecl *PD = ParmVarDecl::Create(
8449 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8450 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8451 PD->setScopeInfo(0, I);
8452 PD->setImplicit();
8453 ParamDecls.push_back(PD);
8454 ProtoLoc.setArg(I, PD);
8455 }
8456
8457 // Set up the new constructor.
8458 DerivedCtor->setAccess(BaseCtor->getAccess());
8459 DerivedCtor->setParams(ParamDecls);
8460 DerivedCtor->setInheritedConstructor(BaseCtor);
8461 if (BaseCtor->isDeleted())
8462 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8463
8464 // If this is a constructor template, build the template declaration.
8465 if (TemplateParams) {
8466 FunctionTemplateDecl *DerivedTemplate =
8467 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8468 TemplateParams, DerivedCtor);
8469 DerivedTemplate->setAccess(BaseCtor->getAccess());
8470 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8471 Derived->addDecl(DerivedTemplate);
8472 } else {
8473 Derived->addDecl(DerivedCtor);
8474 }
8475
8476 Entry.BaseCtor = BaseCtor;
8477 Entry.DerivedCtor = DerivedCtor;
8478 }
8479
8480 Sema &SemaRef;
8481 CXXRecordDecl *Derived;
8482 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8483 MapType Map;
8484};
8485}
8486
8487void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8488 // Defer declaring the inheriting constructors until the class is
8489 // instantiated.
8490 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008491 return;
8492
Richard Smith185be182013-04-10 05:48:59 +00008493 // Find base classes from which we might inherit constructors.
8494 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8495 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8496 BaseE = ClassDecl->bases_end();
8497 BaseIt != BaseE; ++BaseIt)
8498 if (BaseIt->getInheritConstructors())
8499 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008500
Richard Smith185be182013-04-10 05:48:59 +00008501 // Go no further if we're not inheriting any constructors.
8502 if (InheritedBases.empty())
8503 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008504
Richard Smith185be182013-04-10 05:48:59 +00008505 // Declare the inherited constructors.
8506 InheritingConstructorInfo ICI(*this, ClassDecl);
8507 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8508 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008509}
8510
Richard Smithc2bc61b2013-03-18 21:12:30 +00008511void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8512 CXXConstructorDecl *Constructor) {
8513 CXXRecordDecl *ClassDecl = Constructor->getParent();
8514 assert(Constructor->getInheritedConstructor() &&
8515 !Constructor->doesThisDeclarationHaveABody() &&
8516 !Constructor->isDeleted());
8517
8518 SynthesizedFunctionScope Scope(*this, Constructor);
8519 DiagnosticErrorTrap Trap(Diags);
8520 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8521 Trap.hasErrorOccurred()) {
8522 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8523 << Context.getTagDeclType(ClassDecl);
8524 Constructor->setInvalidDecl();
8525 return;
8526 }
8527
8528 SourceLocation Loc = Constructor->getLocation();
8529 Constructor->setBody(new (Context) CompoundStmt(Loc));
8530
Eli Friedman276dd182013-09-05 00:02:25 +00008531 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008532 MarkVTableUsed(CurrentLocation, ClassDecl);
8533
8534 if (ASTMutationListener *L = getASTMutationListener()) {
8535 L->CompletedImplicitDefinition(Constructor);
8536 }
8537}
8538
8539
Alexis Huntf91729462011-05-12 22:46:25 +00008540Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008541Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8542 CXXRecordDecl *ClassDecl = MD->getParent();
8543
Douglas Gregorf1203042010-07-01 19:09:28 +00008544 // C++ [except.spec]p14:
8545 // An implicitly declared special member function (Clause 12) shall have
8546 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008547 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008548 if (ClassDecl->isInvalidDecl())
8549 return ExceptSpec;
8550
Douglas Gregorf1203042010-07-01 19:09:28 +00008551 // Direct base-class destructors.
8552 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8553 BEnd = ClassDecl->bases_end();
8554 B != BEnd; ++B) {
8555 if (B->isVirtual()) // Handled below.
8556 continue;
8557
8558 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008559 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008560 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008561 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008562
Douglas Gregorf1203042010-07-01 19:09:28 +00008563 // Virtual base-class destructors.
8564 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8565 BEnd = ClassDecl->vbases_end();
8566 B != BEnd; ++B) {
8567 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008568 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008569 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008570 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008571
Douglas Gregorf1203042010-07-01 19:09:28 +00008572 // Field destructors.
8573 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8574 FEnd = ClassDecl->field_end();
8575 F != FEnd; ++F) {
8576 if (const RecordType *RecordTy
8577 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008578 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008579 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008580 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008581
Alexis Huntf91729462011-05-12 22:46:25 +00008582 return ExceptSpec;
8583}
8584
8585CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8586 // C++ [class.dtor]p2:
8587 // If a class has no user-declared destructor, a destructor is
8588 // declared implicitly. An implicitly-declared destructor is an
8589 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008590 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008591
Richard Smith8bf22e52012-11-29 01:34:07 +00008592 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8593 if (DSM.isAlreadyBeingDeclared())
8594 return 0;
8595
Douglas Gregor7454c562010-07-02 20:37:36 +00008596 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008597 CanQualType ClassType
8598 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008599 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008600 DeclarationName Name
8601 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008602 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008603 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008604 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8605 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008606 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008607 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008608 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008609 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008610
8611 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008612 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008613 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008614
Richard Smith6b02d462012-12-08 08:32:28 +00008615 AddOverriddenMethods(ClassDecl, Destructor);
8616
8617 // We don't need to use SpecialMemberIsTrivial here; triviality for
8618 // destructors is easy to compute.
8619 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8620
8621 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008622 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008623
Douglas Gregor7454c562010-07-02 20:37:36 +00008624 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008625 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008626
Douglas Gregor7454c562010-07-02 20:37:36 +00008627 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008628 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008629 PushOnScopeChains(Destructor, S, false);
8630 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008631
Douglas Gregorf1203042010-07-01 19:09:28 +00008632 return Destructor;
8633}
8634
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008635void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008636 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008637 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008638 !Destructor->doesThisDeclarationHaveABody() &&
8639 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008640 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008641 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008642 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008643
Douglas Gregor54818f02010-05-12 16:39:35 +00008644 if (Destructor->isInvalidDecl())
8645 return;
8646
Eli Friedmaneaf34142012-10-18 20:14:08 +00008647 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008648
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008649 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008650 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8651 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008652
Douglas Gregor54818f02010-05-12 16:39:35 +00008653 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008654 Diag(CurrentLocation, diag::note_member_synthesized_at)
8655 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8656
8657 Destructor->setInvalidDecl();
8658 return;
8659 }
8660
Douglas Gregor73193272010-09-20 16:48:21 +00008661 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008662 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008663 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008664 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008665
8666 if (ASTMutationListener *L = getASTMutationListener()) {
8667 L->CompletedImplicitDefinition(Destructor);
8668 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008669}
8670
Richard Smith84973e52012-04-21 18:42:51 +00008671/// \brief Perform any semantic analysis which needs to be delayed until all
8672/// pending class member declarations have been parsed.
8673void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008674 // If the context is an invalid C++ class, just suppress these checks.
8675 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8676 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008677 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008678 DelayedDestructorExceptionSpecChecks.clear();
8679 return;
8680 }
8681 }
Richard Smith84973e52012-04-21 18:42:51 +00008682}
8683
Richard Smithd3b5c9082012-07-27 04:22:15 +00008684void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8685 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008686 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008687 "adjusting dtor exception specs was introduced in c++11");
8688
Sebastian Redl623ea822011-05-19 05:13:44 +00008689 // C++11 [class.dtor]p3:
8690 // A declaration of a destructor that does not have an exception-
8691 // specification is implicitly considered to have the same exception-
8692 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008693 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008694 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008695 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008696 return;
8697
Chandler Carruth9a797572011-09-20 04:55:26 +00008698 // Replace the destructor's type, building off the existing one. Fortunately,
8699 // the only thing of interest in the destructor type is its extended info.
8700 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008701 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8702 EPI.ExceptionSpecType = EST_Unevaluated;
8703 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008704 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008705
Sebastian Redl623ea822011-05-19 05:13:44 +00008706 // FIXME: If the destructor has a body that could throw, and the newly created
8707 // spec doesn't allow exceptions, we should emit a warning, because this
8708 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008709 // However, we don't have a body or an exception specification yet, so it
8710 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008711}
8712
Pavel Labath58934982013-08-30 08:52:28 +00008713namespace {
8714/// \brief An abstract base class for all helper classes used in building the
8715// copy/move operators. These classes serve as factory functions and help us
8716// avoid using the same Expr* in the AST twice.
8717class ExprBuilder {
8718 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8719 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8720
8721protected:
8722 static Expr *assertNotNull(Expr *E) {
8723 assert(E && "Expression construction must not fail.");
8724 return E;
8725 }
8726
8727public:
8728 ExprBuilder() {}
8729 virtual ~ExprBuilder() {}
8730
8731 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8732};
8733
8734class RefBuilder: public ExprBuilder {
8735 VarDecl *Var;
8736 QualType VarType;
8737
8738public:
8739 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8740 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8741 }
8742
8743 RefBuilder(VarDecl *Var, QualType VarType)
8744 : Var(Var), VarType(VarType) {}
8745};
8746
8747class ThisBuilder: public ExprBuilder {
8748public:
8749 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8750 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8751 }
8752};
8753
8754class CastBuilder: public ExprBuilder {
8755 const ExprBuilder &Builder;
8756 QualType Type;
8757 ExprValueKind Kind;
8758 const CXXCastPath &Path;
8759
8760public:
8761 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8762 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8763 CK_UncheckedDerivedToBase, Kind,
8764 &Path).take());
8765 }
8766
8767 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8768 const CXXCastPath &Path)
8769 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8770};
8771
8772class DerefBuilder: public ExprBuilder {
8773 const ExprBuilder &Builder;
8774
8775public:
8776 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8777 return assertNotNull(
8778 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8779 }
8780
8781 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8782};
8783
8784class MemberBuilder: public ExprBuilder {
8785 const ExprBuilder &Builder;
8786 QualType Type;
8787 CXXScopeSpec SS;
8788 bool IsArrow;
8789 LookupResult &MemberLookup;
8790
8791public:
8792 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8793 return assertNotNull(S.BuildMemberReferenceExpr(
8794 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8795 MemberLookup, 0).take());
8796 }
8797
8798 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8799 LookupResult &MemberLookup)
8800 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8801 MemberLookup(MemberLookup) {}
8802};
8803
8804class MoveCastBuilder: public ExprBuilder {
8805 const ExprBuilder &Builder;
8806
8807public:
8808 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8809 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8810 }
8811
8812 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8813};
8814
8815class LvalueConvBuilder: public ExprBuilder {
8816 const ExprBuilder &Builder;
8817
8818public:
8819 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8820 return assertNotNull(
8821 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8822 }
8823
8824 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8825};
8826
8827class SubscriptBuilder: public ExprBuilder {
8828 const ExprBuilder &Base;
8829 const ExprBuilder &Index;
8830
8831public:
8832 virtual Expr *build(Sema &S, SourceLocation Loc) const
8833 LLVM_OVERRIDE {
8834 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8835 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8836 }
8837
8838 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8839 : Base(Base), Index(Index) {}
8840};
8841
8842} // end anonymous namespace
8843
Richard Smith41ae3282012-11-14 00:50:40 +00008844/// When generating a defaulted copy or move assignment operator, if a field
8845/// should be copied with __builtin_memcpy rather than via explicit assignments,
8846/// do so. This optimization only applies for arrays of scalars, and for arrays
8847/// of class type where the selected copy/move-assignment operator is trivial.
8848static StmtResult
8849buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008850 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008851 // Compute the size of the memory buffer to be copied.
8852 QualType SizeType = S.Context.getSizeType();
8853 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8854 S.Context.getTypeSizeInChars(T).getQuantity());
8855
8856 // Take the address of the field references for "from" and "to". We
8857 // directly construct UnaryOperators here because semantic analysis
8858 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008859 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008860 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8861 S.Context.getPointerType(From->getType()),
8862 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008863 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008864 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8865 S.Context.getPointerType(To->getType()),
8866 VK_RValue, OK_Ordinary, Loc);
8867
8868 const Type *E = T->getBaseElementTypeUnsafe();
8869 bool NeedsCollectableMemCpy =
8870 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8871
8872 // Create a reference to the __builtin_objc_memmove_collectable function
8873 StringRef MemCpyName = NeedsCollectableMemCpy ?
8874 "__builtin_objc_memmove_collectable" :
8875 "__builtin_memcpy";
8876 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8877 Sema::LookupOrdinaryName);
8878 S.LookupName(R, S.TUScope, true);
8879
8880 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8881 if (!MemCpy)
8882 // Something went horribly wrong earlier, and we will have complained
8883 // about it.
8884 return StmtError();
8885
8886 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8887 VK_RValue, Loc, 0);
8888 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8889
8890 Expr *CallArgs[] = {
8891 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8892 };
8893 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8894 Loc, CallArgs, Loc);
8895
8896 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8897 return S.Owned(Call.takeAs<Stmt>());
8898}
8899
Sebastian Redl22653ba2011-08-30 19:58:05 +00008900/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008901/// \c To.
8902///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008903/// This routine is used to copy/move the members of a class with an
8904/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008905/// copied are arrays, this routine builds for loops to copy them.
8906///
8907/// \param S The Sema object used for type-checking.
8908///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008909/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008910///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008911/// \param T The type of the expressions being copied/moved. Both expressions
8912/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008913///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008914/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008915///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008916/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008917///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008918/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008919/// Otherwise, it's a non-static member subobject.
8920///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008921/// \param Copying Whether we're copying or moving.
8922///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008923/// \param Depth Internal parameter recording the depth of the recursion.
8924///
Richard Smith41ae3282012-11-14 00:50:40 +00008925/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8926/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008927static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008928buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008929 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008930 bool CopyingBaseSubobject, bool Copying,
8931 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008932 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008933 // Each subobject is assigned in the manner appropriate to its type:
8934 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008935 // - if the subobject is of class type, as if by a call to operator= with
8936 // the subobject as the object expression and the corresponding
8937 // subobject of x as a single function argument (as if by explicit
8938 // qualification; that is, ignoring any possible virtual overriding
8939 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008940 //
8941 // C++03 [class.copy]p13:
8942 // - if the subobject is of class type, the copy assignment operator for
8943 // the class is used (as if by explicit qualification; that is,
8944 // ignoring any possible virtual overriding functions in more derived
8945 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008946 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8947 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008948
Douglas Gregorb139cd52010-05-01 20:49:11 +00008949 // Look for operator=.
8950 DeclarationName Name
8951 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8952 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8953 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008954
Richard Smith52c0b582012-11-13 00:54:12 +00008955 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8956 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008957 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008958 LookupResult::Filter F = OpLookup.makeFilter();
8959 while (F.hasNext()) {
8960 NamedDecl *D = F.next();
8961 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8962 if (Method->isCopyAssignmentOperator() ||
8963 (!Copying && Method->isMoveAssignmentOperator()))
8964 continue;
8965
8966 F.erase();
8967 }
8968 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008969 }
Richard Smith52c0b582012-11-13 00:54:12 +00008970
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008971 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008972 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008973 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008974 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008975 // ambiguities), we need to cast "this" to that subobject type; to
8976 // ensure that we don't go through the virtual call mechanism, we need
8977 // to qualify the operator= name with the base class (see below). However,
8978 // this means that if the base class has a protected copy assignment
8979 // operator, the protected member access check will fail. So, we
8980 // rewrite "protected" access to "public" access in this case, since we
8981 // know by construction that we're calling from a derived class.
8982 if (CopyingBaseSubobject) {
8983 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8984 L != LEnd; ++L) {
8985 if (L.getAccess() == AS_protected)
8986 L.setAccess(AS_public);
8987 }
8988 }
Richard Smith52c0b582012-11-13 00:54:12 +00008989
Douglas Gregorb139cd52010-05-01 20:49:11 +00008990 // Create the nested-name-specifier that will be used to qualify the
8991 // reference to operator=; this is required to suppress the virtual
8992 // call mechanism.
8993 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00008994 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00008995 SS.MakeTrivial(S.Context,
8996 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00008997 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00008998 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00008999
Douglas Gregorb139cd52010-05-01 20:49:11 +00009000 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009001 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009002 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9003 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009004 /*FirstQualifierInScope=*/0,
9005 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009006 /*TemplateArgs=*/0,
9007 /*SuppressQualifierCheck=*/true);
9008 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009009 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009010
Douglas Gregorb139cd52010-05-01 20:49:11 +00009011 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009012
Pavel Labath58934982013-08-30 08:52:28 +00009013 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009014 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009015 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009016 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009017 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009018 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009019
Richard Smith41ae3282012-11-14 00:50:40 +00009020 // If we built a call to a trivial 'operator=' while copying an array,
9021 // bail out. We'll replace the whole shebang with a memcpy.
9022 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9023 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9024 return StmtResult((Stmt*)0);
9025
Richard Smith52c0b582012-11-13 00:54:12 +00009026 // Convert to an expression-statement, and clean up any produced
9027 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009028 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009029 }
John McCallab8c2732010-03-16 06:11:48 +00009030
Richard Smith52c0b582012-11-13 00:54:12 +00009031 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009032 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009033 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009034 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009035 ExprResult Assignment = S.CreateBuiltinBinOp(
9036 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009037 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009038 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009039 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009040 }
Richard Smith52c0b582012-11-13 00:54:12 +00009041
9042 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009043 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009044
Douglas Gregorb139cd52010-05-01 20:49:11 +00009045 // Construct a loop over the array bounds, e.g.,
9046 //
9047 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9048 //
9049 // that will copy each of the array elements.
9050 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009051
Douglas Gregorb139cd52010-05-01 20:49:11 +00009052 // Create the iteration variable.
9053 IdentifierInfo *IterationVarName = 0;
9054 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009055 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009056 llvm::raw_svector_ostream OS(Str);
9057 OS << "__i" << Depth;
9058 IterationVarName = &S.Context.Idents.get(OS.str());
9059 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009060 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009061 IterationVarName, SizeType,
9062 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009063 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009064
Douglas Gregorb139cd52010-05-01 20:49:11 +00009065 // Initialize the iteration variable to zero.
9066 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009067 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009068
Pavel Labath58934982013-08-30 08:52:28 +00009069 // Creates a reference to the iteration variable.
9070 RefBuilder IterationVarRef(IterationVar, SizeType);
9071 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009072
Douglas Gregorb139cd52010-05-01 20:49:11 +00009073 // Create the DeclStmt that holds the iteration variable.
9074 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009075
Douglas Gregorb139cd52010-05-01 20:49:11 +00009076 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009077 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9078 MoveCastBuilder FromIndexMove(FromIndexCopy);
9079 const ExprBuilder *FromIndex;
9080 if (Copying)
9081 FromIndex = &FromIndexCopy;
9082 else
9083 FromIndex = &FromIndexMove;
9084
9085 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009086
9087 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009088 StmtResult Copy =
9089 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009090 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009091 Copying, Depth + 1);
9092 // Bail out if copying fails or if we determined that we should use memcpy.
9093 if (Copy.isInvalid() || !Copy.get())
9094 return Copy;
9095
9096 // Create the comparison against the array bound.
9097 llvm::APInt Upper
9098 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9099 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009100 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009101 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9102 BO_NE, S.Context.BoolTy,
9103 VK_RValue, OK_Ordinary, Loc, false);
9104
9105 // Create the pre-increment of the iteration variable.
9106 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009107 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9108 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009109
Douglas Gregorb139cd52010-05-01 20:49:11 +00009110 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009111 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009112 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009113 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009114 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009115}
9116
Richard Smith41ae3282012-11-14 00:50:40 +00009117static StmtResult
9118buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009119 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009120 bool CopyingBaseSubobject, bool Copying) {
9121 // Maybe we should use a memcpy?
9122 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9123 T.isTriviallyCopyableType(S.Context))
9124 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9125
9126 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9127 CopyingBaseSubobject,
9128 Copying, 0));
9129
9130 // If we ended up picking a trivial assignment operator for an array of a
9131 // non-trivially-copyable class type, just emit a memcpy.
9132 if (!Result.isInvalid() && !Result.get())
9133 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9134
9135 return Result;
9136}
9137
Richard Smithd3b5c9082012-07-27 04:22:15 +00009138Sema::ImplicitExceptionSpecification
9139Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9140 CXXRecordDecl *ClassDecl = MD->getParent();
9141
9142 ImplicitExceptionSpecification ExceptSpec(*this);
9143 if (ClassDecl->isInvalidDecl())
9144 return ExceptSpec;
9145
9146 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9147 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9148 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9149
Douglas Gregor68e11362010-07-01 17:48:08 +00009150 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009151 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009152 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009153
9154 // It is unspecified whether or not an implicit copy assignment operator
9155 // attempts to deduplicate calls to assignment operators of virtual bases are
9156 // made. As such, this exception specification is effectively unspecified.
9157 // Based on a similar decision made for constness in C++0x, we're erring on
9158 // the side of assuming such calls to be made regardless of whether they
9159 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00009160 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9161 BaseEnd = ClassDecl->bases_end();
9162 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009163 if (Base->isVirtual())
9164 continue;
9165
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009166 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00009167 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009168 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9169 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009170 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009171 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009172
9173 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9174 BaseEnd = ClassDecl->vbases_end();
9175 Base != BaseEnd; ++Base) {
9176 CXXRecordDecl *BaseClassDecl
9177 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9178 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9179 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009180 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009181 }
9182
Douglas Gregor68e11362010-07-01 17:48:08 +00009183 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9184 FieldEnd = ClassDecl->field_end();
9185 Field != FieldEnd;
9186 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009187 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009188 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9189 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009190 LookupCopyingAssignment(FieldClassDecl,
9191 ArgQuals | FieldType.getCVRQualifiers(),
9192 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009193 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009194 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009195 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009196
Richard Smithd3b5c9082012-07-27 04:22:15 +00009197 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009198}
9199
9200CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9201 // Note: The following rules are largely analoguous to the copy
9202 // constructor rules. Note that virtual bases are not taken into account
9203 // for determining the argument type of the operator. Note also that
9204 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009205 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009206
Richard Smith8bf22e52012-11-29 01:34:07 +00009207 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9208 if (DSM.isAlreadyBeingDeclared())
9209 return 0;
9210
Alexis Hunt119f3652011-05-14 05:23:20 +00009211 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9212 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009213 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9214 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009215 ArgType = ArgType.withConst();
9216 ArgType = Context.getLValueReferenceType(ArgType);
9217
Richard Smith99005e62013-05-07 03:19:20 +00009218 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9219 CXXCopyAssignment,
9220 Const);
9221
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009222 // An implicitly-declared copy assignment operator is an inline public
9223 // member of its class.
9224 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009225 SourceLocation ClassLoc = ClassDecl->getLocation();
9226 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009227 CXXMethodDecl *CopyAssignment =
9228 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9229 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9230 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009231 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009232 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009233 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009234
9235 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009236 FunctionProtoType::ExtProtoInfo EPI =
9237 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009238 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009239
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009240 // Add the parameter to the operator.
9241 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009242 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009243 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009244 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009245 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009246
Richard Smith6b02d462012-12-08 08:32:28 +00009247 AddOverriddenMethods(ClassDecl, CopyAssignment);
9248
9249 CopyAssignment->setTrivial(
9250 ClassDecl->needsOverloadResolutionForCopyAssignment()
9251 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9252 : ClassDecl->hasTrivialCopyAssignment());
9253
Richard Smith852265f2012-03-30 20:53:28 +00009254 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009255 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009256
Richard Smith6b02d462012-12-08 08:32:28 +00009257 // Note that we have added this copy-assignment operator.
9258 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9259
9260 if (Scope *S = getScopeForContext(ClassDecl))
9261 PushOnScopeChains(CopyAssignment, S, false);
9262 ClassDecl->addDecl(CopyAssignment);
9263
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009264 return CopyAssignment;
9265}
9266
Richard Smithd577fbb2013-06-13 03:23:42 +00009267/// Diagnose an implicit copy operation for a class which is odr-used, but
9268/// which is deprecated because the class has a user-declared copy constructor,
9269/// copy assignment operator, or destructor.
9270static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9271 SourceLocation UseLoc) {
9272 assert(CopyOp->isImplicit());
9273
9274 CXXRecordDecl *RD = CopyOp->getParent();
9275 CXXMethodDecl *UserDeclaredOperation = 0;
9276
9277 // In Microsoft mode, assignment operations don't affect constructors and
9278 // vice versa.
9279 if (RD->hasUserDeclaredDestructor()) {
9280 UserDeclaredOperation = RD->getDestructor();
9281 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9282 RD->hasUserDeclaredCopyConstructor() &&
9283 !S.getLangOpts().MicrosoftMode) {
9284 // Find any user-declared copy constructor.
9285 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9286 E = RD->ctor_end(); I != E; ++I) {
9287 if (I->isCopyConstructor()) {
9288 UserDeclaredOperation = *I;
9289 break;
9290 }
9291 }
9292 assert(UserDeclaredOperation);
9293 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9294 RD->hasUserDeclaredCopyAssignment() &&
9295 !S.getLangOpts().MicrosoftMode) {
9296 // Find any user-declared move assignment operator.
9297 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9298 E = RD->method_end(); I != E; ++I) {
9299 if (I->isCopyAssignmentOperator()) {
9300 UserDeclaredOperation = *I;
9301 break;
9302 }
9303 }
9304 assert(UserDeclaredOperation);
9305 }
9306
9307 if (UserDeclaredOperation) {
9308 S.Diag(UserDeclaredOperation->getLocation(),
9309 diag::warn_deprecated_copy_operation)
9310 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9311 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9312 S.Diag(UseLoc, diag::note_member_synthesized_at)
9313 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9314 : Sema::CXXCopyAssignment)
9315 << RD;
9316 }
9317}
9318
Douglas Gregorb139cd52010-05-01 20:49:11 +00009319void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9320 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009321 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009322 CopyAssignOperator->isOverloadedOperator() &&
9323 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009324 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9325 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009326 "DefineImplicitCopyAssignment called for wrong function");
9327
9328 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9329
9330 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9331 CopyAssignOperator->setInvalidDecl();
9332 return;
9333 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009334
9335 // C++11 [class.copy]p18:
9336 // The [definition of an implicitly declared copy assignment operator] is
9337 // deprecated if the class has a user-declared copy constructor or a
9338 // user-declared destructor.
9339 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9340 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9341
Eli Friedman276dd182013-09-05 00:02:25 +00009342 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009343
Eli Friedmaneaf34142012-10-18 20:14:08 +00009344 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009345 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009346
9347 // C++0x [class.copy]p30:
9348 // The implicitly-defined or explicitly-defaulted copy assignment operator
9349 // for a non-union class X performs memberwise copy assignment of its
9350 // subobjects. The direct base classes of X are assigned first, in the
9351 // order of their declaration in the base-specifier-list, and then the
9352 // immediate non-static data members of X are assigned, in the order in
9353 // which they were declared in the class definition.
9354
9355 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009356 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009357
9358 // The parameter for the "other" object, which we are copying from.
9359 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9360 Qualifiers OtherQuals = Other->getType().getQualifiers();
9361 QualType OtherRefType = Other->getType();
9362 if (const LValueReferenceType *OtherRef
9363 = OtherRefType->getAs<LValueReferenceType>()) {
9364 OtherRefType = OtherRef->getPointeeType();
9365 OtherQuals = OtherRefType.getQualifiers();
9366 }
9367
9368 // Our location for everything implicitly-generated.
9369 SourceLocation Loc = CopyAssignOperator->getLocation();
9370
Pavel Labath58934982013-08-30 08:52:28 +00009371 // Builds a DeclRefExpr for the "other" object.
9372 RefBuilder OtherRef(Other, OtherRefType);
9373
9374 // Builds the "this" pointer.
9375 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009376
9377 // Assign base classes.
9378 bool Invalid = false;
9379 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9380 E = ClassDecl->bases_end(); Base != E; ++Base) {
9381 // Form the assignment:
9382 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9383 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009384 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009385 Invalid = true;
9386 continue;
9387 }
9388
John McCallcf142162010-08-07 06:22:56 +00009389 CXXCastPath BasePath;
9390 BasePath.push_back(Base);
9391
Douglas Gregorb139cd52010-05-01 20:49:11 +00009392 // Construct the "from" expression, which is an implicit cast to the
9393 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009394 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9395 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009396
9397 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009398 DerefBuilder DerefThis(This);
9399 CastBuilder To(DerefThis,
9400 Context.getCVRQualifiedType(
9401 BaseType, CopyAssignOperator->getTypeQualifiers()),
9402 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403
9404 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009405 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009406 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009407 /*CopyingBaseSubobject=*/true,
9408 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009409 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009410 Diag(CurrentLocation, diag::note_member_synthesized_at)
9411 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9412 CopyAssignOperator->setInvalidDecl();
9413 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009414 }
9415
9416 // Success! Record the copy.
9417 Statements.push_back(Copy.takeAs<Expr>());
9418 }
9419
Douglas Gregorb139cd52010-05-01 20:49:11 +00009420 // Assign non-static members.
9421 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9422 FieldEnd = ClassDecl->field_end();
9423 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009424 if (Field->isUnnamedBitfield())
9425 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009426
9427 if (Field->isInvalidDecl()) {
9428 Invalid = true;
9429 continue;
9430 }
9431
Douglas Gregorb139cd52010-05-01 20:49:11 +00009432 // Check for members of reference type; we can't copy those.
9433 if (Field->getType()->isReferenceType()) {
9434 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9435 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9436 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009437 Diag(CurrentLocation, diag::note_member_synthesized_at)
9438 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009439 Invalid = true;
9440 continue;
9441 }
9442
9443 // Check for members of const-qualified, non-class type.
9444 QualType BaseType = Context.getBaseElementType(Field->getType());
9445 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9447 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9448 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009449 Diag(CurrentLocation, diag::note_member_synthesized_at)
9450 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009451 Invalid = true;
9452 continue;
9453 }
John McCall1b1a1db2011-06-17 00:18:42 +00009454
9455 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009456 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9457 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009458
9459 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009460 if (FieldType->isIncompleteArrayType()) {
9461 assert(ClassDecl->hasFlexibleArrayMember() &&
9462 "Incomplete array type is not valid");
9463 continue;
9464 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009465
9466 // Build references to the field in the object we're copying from and to.
9467 CXXScopeSpec SS; // Intentionally empty
9468 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9469 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009470 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009471 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009472
9473 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9474
9475 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009476
Douglas Gregorb139cd52010-05-01 20:49:11 +00009477 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009478 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009479 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009480 /*CopyingBaseSubobject=*/false,
9481 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009482 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009483 Diag(CurrentLocation, diag::note_member_synthesized_at)
9484 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9485 CopyAssignOperator->setInvalidDecl();
9486 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009487 }
9488
9489 // Success! Record the copy.
9490 Statements.push_back(Copy.takeAs<Stmt>());
9491 }
9492
9493 if (!Invalid) {
9494 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009495 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009496
John McCalldadc5752010-08-24 06:29:42 +00009497 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009498 if (Return.isInvalid())
9499 Invalid = true;
9500 else {
9501 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009502
9503 if (Trap.hasErrorOccurred()) {
9504 Diag(CurrentLocation, diag::note_member_synthesized_at)
9505 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9506 Invalid = true;
9507 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009508 }
9509 }
9510
9511 if (Invalid) {
9512 CopyAssignOperator->setInvalidDecl();
9513 return;
9514 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009515
9516 StmtResult Body;
9517 {
9518 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009519 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009520 /*isStmtExpr=*/false);
9521 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9522 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009523 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009524
9525 if (ASTMutationListener *L = getASTMutationListener()) {
9526 L->CompletedImplicitDefinition(CopyAssignOperator);
9527 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009528}
9529
Sebastian Redl22653ba2011-08-30 19:58:05 +00009530Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009531Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9532 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009533
Richard Smithd3b5c9082012-07-27 04:22:15 +00009534 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009535 if (ClassDecl->isInvalidDecl())
9536 return ExceptSpec;
9537
9538 // C++0x [except.spec]p14:
9539 // An implicitly declared special member function (Clause 12) shall have an
9540 // exception-specification. [...]
9541
9542 // It is unspecified whether or not an implicit move assignment operator
9543 // attempts to deduplicate calls to assignment operators of virtual bases are
9544 // made. As such, this exception specification is effectively unspecified.
9545 // Based on a similar decision made for constness in C++0x, we're erring on
9546 // the side of assuming such calls to be made regardless of whether they
9547 // actually happen.
9548 // Note that a move constructor is not implicitly declared when there are
9549 // virtual bases, but it can still be user-declared and explicitly defaulted.
9550 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9551 BaseEnd = ClassDecl->bases_end();
9552 Base != BaseEnd; ++Base) {
9553 if (Base->isVirtual())
9554 continue;
9555
9556 CXXRecordDecl *BaseClassDecl
9557 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9558 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009559 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009560 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009561 }
9562
9563 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9564 BaseEnd = ClassDecl->vbases_end();
9565 Base != BaseEnd; ++Base) {
9566 CXXRecordDecl *BaseClassDecl
9567 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9568 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009569 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009570 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009571 }
9572
9573 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9574 FieldEnd = ClassDecl->field_end();
9575 Field != FieldEnd;
9576 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009577 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009578 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009579 if (CXXMethodDecl *MoveAssign =
9580 LookupMovingAssignment(FieldClassDecl,
9581 FieldType.getCVRQualifiers(),
9582 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009583 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009584 }
9585 }
9586
9587 return ExceptSpec;
9588}
9589
9590CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009591 assert(ClassDecl->needsImplicitMoveAssignment());
9592
Richard Smith8bf22e52012-11-29 01:34:07 +00009593 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9594 if (DSM.isAlreadyBeingDeclared())
9595 return 0;
9596
Sebastian Redl22653ba2011-08-30 19:58:05 +00009597 // Note: The following rules are largely analoguous to the move
9598 // constructor rules.
9599
Sebastian Redl22653ba2011-08-30 19:58:05 +00009600 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9601 QualType RetType = Context.getLValueReferenceType(ArgType);
9602 ArgType = Context.getRValueReferenceType(ArgType);
9603
Richard Smith99005e62013-05-07 03:19:20 +00009604 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9605 CXXMoveAssignment,
9606 false);
9607
Sebastian Redl22653ba2011-08-30 19:58:05 +00009608 // An implicitly-declared move assignment operator is an inline public
9609 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009610 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9611 SourceLocation ClassLoc = ClassDecl->getLocation();
9612 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009613 CXXMethodDecl *MoveAssignment =
9614 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9615 /*TInfo=*/0, /*StorageClass=*/SC_None,
9616 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009617 MoveAssignment->setAccess(AS_public);
9618 MoveAssignment->setDefaulted();
9619 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009620
Richard Smithd3b5c9082012-07-27 04:22:15 +00009621 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009622 FunctionProtoType::ExtProtoInfo EPI =
9623 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009624 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009625
Sebastian Redl22653ba2011-08-30 19:58:05 +00009626 // Add the parameter to the operator.
9627 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9628 ClassLoc, ClassLoc, /*Id=*/0,
9629 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009630 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009631 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009632
Richard Smith6b02d462012-12-08 08:32:28 +00009633 AddOverriddenMethods(ClassDecl, MoveAssignment);
9634
9635 MoveAssignment->setTrivial(
9636 ClassDecl->needsOverloadResolutionForMoveAssignment()
9637 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9638 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009639
Richard Smithd951a1d2012-02-18 02:02:13 +00009640 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009641 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9642 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009643 }
9644
Richard Smith6b02d462012-12-08 08:32:28 +00009645 // Note that we have added this copy-assignment operator.
9646 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9647
Sebastian Redl22653ba2011-08-30 19:58:05 +00009648 if (Scope *S = getScopeForContext(ClassDecl))
9649 PushOnScopeChains(MoveAssignment, S, false);
9650 ClassDecl->addDecl(MoveAssignment);
9651
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652 return MoveAssignment;
9653}
9654
Richard Smithb2504bd2013-11-04 04:26:14 +00009655/// Check if we're implicitly defining a move assignment operator for a class
9656/// with virtual bases. Such a move assignment might move-assign the virtual
9657/// base multiple times.
9658static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9659 SourceLocation CurrentLocation) {
9660 assert(!Class->isDependentContext() && "should not define dependent move");
9661
9662 // Only a virtual base could get implicitly move-assigned multiple times.
9663 // Only a non-trivial move assignment can observe this. We only want to
9664 // diagnose if we implicitly define an assignment operator that assigns
9665 // two base classes, both of which move-assign the same virtual base.
9666 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9667 Class->getNumBases() < 2)
9668 return;
9669
9670 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9671 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9672 VBaseMap VBases;
9673
9674 for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9675 BE = Class->bases_end();
9676 BI != BE; ++BI) {
9677 Worklist.push_back(&*BI);
9678 while (!Worklist.empty()) {
9679 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9680 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9681
9682 // If the base has no non-trivial move assignment operators,
9683 // we don't care about moves from it.
9684 if (!Base->hasNonTrivialMoveAssignment())
9685 continue;
9686
9687 // If there's nothing virtual here, skip it.
9688 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9689 continue;
9690
9691 // If we're not actually going to call a move assignment for this base,
9692 // or the selected move assignment is trivial, skip it.
9693 Sema::SpecialMemberOverloadResult *SMOR =
9694 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9695 /*ConstArg*/false, /*VolatileArg*/false,
9696 /*RValueThis*/true, /*ConstThis*/false,
9697 /*VolatileThis*/false);
9698 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9699 !SMOR->getMethod()->isMoveAssignmentOperator())
9700 continue;
9701
9702 if (BaseSpec->isVirtual()) {
9703 // We're going to move-assign this virtual base, and its move
9704 // assignment operator is not trivial. If this can happen for
9705 // multiple distinct direct bases of Class, diagnose it. (If it
9706 // only happens in one base, we'll diagnose it when synthesizing
9707 // that base class's move assignment operator.)
9708 CXXBaseSpecifier *&Existing =
9709 VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9710 .first->second;
9711 if (Existing && Existing != BI) {
9712 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9713 << Class << Base;
9714 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9715 << (Base->getCanonicalDecl() ==
9716 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9717 << Base << Existing->getType() << Existing->getSourceRange();
9718 S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9719 << (Base->getCanonicalDecl() ==
9720 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9721 << Base << BI->getType() << BaseSpec->getSourceRange();
9722
9723 // Only diagnose each vbase once.
9724 Existing = 0;
9725 }
9726 } else {
9727 // Only walk over bases that have defaulted move assignment operators.
9728 // We assume that any user-provided move assignment operator handles
9729 // the multiple-moves-of-vbase case itself somehow.
9730 if (!SMOR->getMethod()->isDefaulted())
9731 continue;
9732
9733 // We're going to move the base classes of Base. Add them to the list.
9734 for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9735 BE = Base->bases_end();
9736 BI != BE; ++BI)
9737 Worklist.push_back(&*BI);
9738 }
9739 }
9740 }
9741}
9742
Sebastian Redl22653ba2011-08-30 19:58:05 +00009743void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9744 CXXMethodDecl *MoveAssignOperator) {
9745 assert((MoveAssignOperator->isDefaulted() &&
9746 MoveAssignOperator->isOverloadedOperator() &&
9747 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009748 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9749 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009750 "DefineImplicitMoveAssignment called for wrong function");
9751
9752 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9753
9754 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9755 MoveAssignOperator->setInvalidDecl();
9756 return;
9757 }
9758
Eli Friedman276dd182013-09-05 00:02:25 +00009759 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009760
Eli Friedmaneaf34142012-10-18 20:14:08 +00009761 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009762 DiagnosticErrorTrap Trap(Diags);
9763
9764 // C++0x [class.copy]p28:
9765 // The implicitly-defined or move assignment operator for a non-union class
9766 // X performs memberwise move assignment of its subobjects. The direct base
9767 // classes of X are assigned first, in the order of their declaration in the
9768 // base-specifier-list, and then the immediate non-static data members of X
9769 // are assigned, in the order in which they were declared in the class
9770 // definition.
9771
Richard Smithb2504bd2013-11-04 04:26:14 +00009772 // Issue a warning if our implicit move assignment operator will move
9773 // from a virtual base more than once.
9774 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009775
Sebastian Redl22653ba2011-08-30 19:58:05 +00009776 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009777 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009778
9779 // The parameter for the "other" object, which we are move from.
9780 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9781 QualType OtherRefType = Other->getType()->
9782 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009783 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009784 "Bad argument type of defaulted move assignment");
9785
9786 // Our location for everything implicitly-generated.
9787 SourceLocation Loc = MoveAssignOperator->getLocation();
9788
Pavel Labath58934982013-08-30 08:52:28 +00009789 // Builds a reference to the "other" object.
9790 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009791 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009792 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009793
Pavel Labath58934982013-08-30 08:52:28 +00009794 // Builds the "this" pointer.
9795 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009796
Sebastian Redl22653ba2011-08-30 19:58:05 +00009797 // Assign base classes.
9798 bool Invalid = false;
9799 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9800 E = ClassDecl->bases_end(); Base != E; ++Base) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009801 // C++11 [class.copy]p28:
9802 // It is unspecified whether subobjects representing virtual base classes
9803 // are assigned more than once by the implicitly-defined copy assignment
9804 // operator.
9805 // FIXME: Do not assign to a vbase that will be assigned by some other base
9806 // class. For a move-assignment, this can result in the vbase being moved
9807 // multiple times.
9808
Sebastian Redl22653ba2011-08-30 19:58:05 +00009809 // Form the assignment:
9810 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9811 QualType BaseType = Base->getType().getUnqualifiedType();
9812 if (!BaseType->isRecordType()) {
9813 Invalid = true;
9814 continue;
9815 }
9816
9817 CXXCastPath BasePath;
9818 BasePath.push_back(Base);
9819
9820 // Construct the "from" expression, which is an implicit cast to the
9821 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009822 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009823
9824 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009825 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009826
9827 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009828 CastBuilder To(DerefThis,
9829 Context.getCVRQualifiedType(
9830 BaseType, MoveAssignOperator->getTypeQualifiers()),
9831 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832
9833 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009834 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009835 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009836 /*CopyingBaseSubobject=*/true,
9837 /*Copying=*/false);
9838 if (Move.isInvalid()) {
9839 Diag(CurrentLocation, diag::note_member_synthesized_at)
9840 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9841 MoveAssignOperator->setInvalidDecl();
9842 return;
9843 }
9844
9845 // Success! Record the move.
9846 Statements.push_back(Move.takeAs<Expr>());
9847 }
9848
Sebastian Redl22653ba2011-08-30 19:58:05 +00009849 // Assign non-static members.
9850 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9851 FieldEnd = ClassDecl->field_end();
9852 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009853 if (Field->isUnnamedBitfield())
9854 continue;
9855
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009856 if (Field->isInvalidDecl()) {
9857 Invalid = true;
9858 continue;
9859 }
9860
Sebastian Redl22653ba2011-08-30 19:58:05 +00009861 // Check for members of reference type; we can't move those.
9862 if (Field->getType()->isReferenceType()) {
9863 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9864 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9865 Diag(Field->getLocation(), diag::note_declared_at);
9866 Diag(CurrentLocation, diag::note_member_synthesized_at)
9867 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9868 Invalid = true;
9869 continue;
9870 }
9871
9872 // Check for members of const-qualified, non-class type.
9873 QualType BaseType = Context.getBaseElementType(Field->getType());
9874 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9875 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9876 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9877 Diag(Field->getLocation(), diag::note_declared_at);
9878 Diag(CurrentLocation, diag::note_member_synthesized_at)
9879 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9880 Invalid = true;
9881 continue;
9882 }
9883
9884 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009885 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9886 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009887
9888 QualType FieldType = Field->getType().getNonReferenceType();
9889 if (FieldType->isIncompleteArrayType()) {
9890 assert(ClassDecl->hasFlexibleArrayMember() &&
9891 "Incomplete array type is not valid");
9892 continue;
9893 }
9894
9895 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009896 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9897 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009898 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009899 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009900 MemberBuilder From(MoveOther, OtherRefType,
9901 /*IsArrow=*/false, MemberLookup);
9902 MemberBuilder To(This, getCurrentThisType(),
9903 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009904
Pavel Labath58934982013-08-30 08:52:28 +00009905 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009906 "Member reference with rvalue base must be rvalue except for reference "
9907 "members, which aren't allowed for move assignment.");
9908
Sebastian Redl22653ba2011-08-30 19:58:05 +00009909 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009910 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009911 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009912 /*CopyingBaseSubobject=*/false,
9913 /*Copying=*/false);
9914 if (Move.isInvalid()) {
9915 Diag(CurrentLocation, diag::note_member_synthesized_at)
9916 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9917 MoveAssignOperator->setInvalidDecl();
9918 return;
9919 }
Richard Smith11d19592012-11-12 23:33:00 +00009920
Sebastian Redl22653ba2011-08-30 19:58:05 +00009921 // Success! Record the copy.
9922 Statements.push_back(Move.takeAs<Stmt>());
9923 }
9924
9925 if (!Invalid) {
9926 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009927 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009928
9929 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9930 if (Return.isInvalid())
9931 Invalid = true;
9932 else {
9933 Statements.push_back(Return.takeAs<Stmt>());
9934
9935 if (Trap.hasErrorOccurred()) {
9936 Diag(CurrentLocation, diag::note_member_synthesized_at)
9937 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9938 Invalid = true;
9939 }
9940 }
9941 }
9942
9943 if (Invalid) {
9944 MoveAssignOperator->setInvalidDecl();
9945 return;
9946 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009947
9948 StmtResult Body;
9949 {
9950 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009951 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009952 /*isStmtExpr=*/false);
9953 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9954 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009955 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9956
9957 if (ASTMutationListener *L = getASTMutationListener()) {
9958 L->CompletedImplicitDefinition(MoveAssignOperator);
9959 }
9960}
9961
Richard Smithd3b5c9082012-07-27 04:22:15 +00009962Sema::ImplicitExceptionSpecification
9963Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9964 CXXRecordDecl *ClassDecl = MD->getParent();
9965
9966 ImplicitExceptionSpecification ExceptSpec(*this);
9967 if (ClassDecl->isInvalidDecl())
9968 return ExceptSpec;
9969
9970 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9971 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9972 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9973
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009974 // C++ [except.spec]p14:
9975 // An implicitly declared special member function (Clause 12) shall have an
9976 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009977 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9978 BaseEnd = ClassDecl->bases_end();
9979 Base != BaseEnd;
9980 ++Base) {
9981 // Virtual bases are handled below.
9982 if (Base->isVirtual())
9983 continue;
9984
Douglas Gregora6d69502010-07-02 23:41:54 +00009985 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009986 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009987 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009988 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +00009989 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009990 }
9991 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9992 BaseEnd = ClassDecl->vbases_end();
9993 Base != BaseEnd;
9994 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00009995 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00009996 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00009997 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00009998 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +00009999 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010000 }
10001 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10002 FieldEnd = ClassDecl->field_end();
10003 Field != FieldEnd;
10004 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010005 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010006 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10007 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010008 LookupCopyingConstructor(FieldClassDecl,
10009 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010010 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010011 }
10012 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010013
Richard Smithd3b5c9082012-07-27 04:22:15 +000010014 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010015}
10016
10017CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10018 CXXRecordDecl *ClassDecl) {
10019 // C++ [class.copy]p4:
10020 // If the class definition does not explicitly declare a copy
10021 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010022 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010023
Richard Smith8bf22e52012-11-29 01:34:07 +000010024 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10025 if (DSM.isAlreadyBeingDeclared())
10026 return 0;
10027
Alexis Hunt913820d2011-05-13 06:10:58 +000010028 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10029 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010030 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010031 if (Const)
10032 ArgType = ArgType.withConst();
10033 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010034
Richard Smithb5800092012-06-10 05:43:50 +000010035 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10036 CXXCopyConstructor,
10037 Const);
10038
Douglas Gregor54be3392010-07-01 17:57:27 +000010039 DeclarationName Name
10040 = Context.DeclarationNames.getCXXConstructorName(
10041 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010042 SourceLocation ClassLoc = ClassDecl->getLocation();
10043 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010044
10045 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010046 // member of its class.
10047 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010048 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010049 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010050 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010051 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010052 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010053
Richard Smithd3b5c9082012-07-27 04:22:15 +000010054 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010055 FunctionProtoType::ExtProtoInfo EPI =
10056 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010057 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010058 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010059
Douglas Gregor54be3392010-07-01 17:57:27 +000010060 // Add the parameter to the constructor.
10061 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010062 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010063 /*IdentifierInfo=*/0,
10064 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010065 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010066 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010067
Richard Smith6b02d462012-12-08 08:32:28 +000010068 CopyConstructor->setTrivial(
10069 ClassDecl->needsOverloadResolutionForCopyConstructor()
10070 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10071 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010072
Richard Smith852265f2012-03-30 20:53:28 +000010073 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010074 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010075
Richard Smith6b02d462012-12-08 08:32:28 +000010076 // Note that we have declared this constructor.
10077 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10078
10079 if (Scope *S = getScopeForContext(ClassDecl))
10080 PushOnScopeChains(CopyConstructor, S, false);
10081 ClassDecl->addDecl(CopyConstructor);
10082
Douglas Gregor54be3392010-07-01 17:57:27 +000010083 return CopyConstructor;
10084}
10085
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010086void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010087 CXXConstructorDecl *CopyConstructor) {
10088 assert((CopyConstructor->isDefaulted() &&
10089 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010090 !CopyConstructor->doesThisDeclarationHaveABody() &&
10091 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010092 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010093
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010094 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010095 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010096
Richard Smithd577fbb2013-06-13 03:23:42 +000010097 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010098 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010099 // deprecated if the class has a user-declared copy assignment operator
10100 // or a user-declared destructor.
10101 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10102 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10103
Eli Friedmaneaf34142012-10-18 20:14:08 +000010104 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010105 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010106
David Blaikie3fc2f912013-01-17 05:26:25 +000010107 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010108 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010109 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010110 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010111 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010112 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010113 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010114 CopyConstructor->setBody(ActOnCompoundStmt(
10115 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10116 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010117 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010118
Eli Friedman276dd182013-09-05 00:02:25 +000010119 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010120 if (ASTMutationListener *L = getASTMutationListener()) {
10121 L->CompletedImplicitDefinition(CopyConstructor);
10122 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010123}
10124
Sebastian Redl22653ba2011-08-30 19:58:05 +000010125Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010126Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10127 CXXRecordDecl *ClassDecl = MD->getParent();
10128
Sebastian Redl22653ba2011-08-30 19:58:05 +000010129 // C++ [except.spec]p14:
10130 // An implicitly declared special member function (Clause 12) shall have an
10131 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010132 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010133 if (ClassDecl->isInvalidDecl())
10134 return ExceptSpec;
10135
10136 // Direct base-class constructors.
10137 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10138 BEnd = ClassDecl->bases_end();
10139 B != BEnd; ++B) {
10140 if (B->isVirtual()) // Handled below.
10141 continue;
10142
10143 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10144 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010145 CXXConstructorDecl *Constructor =
10146 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010147 // If this is a deleted function, add it anyway. This might be conformant
10148 // with the standard. This might not. I'm not sure. It might not matter.
10149 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010150 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151 }
10152 }
10153
10154 // Virtual base-class constructors.
10155 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10156 BEnd = ClassDecl->vbases_end();
10157 B != BEnd; ++B) {
10158 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10159 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010160 CXXConstructorDecl *Constructor =
10161 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010162 // If this is a deleted function, add it anyway. This might be conformant
10163 // with the standard. This might not. I'm not sure. It might not matter.
10164 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010165 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010166 }
10167 }
10168
10169 // Field constructors.
10170 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10171 FEnd = ClassDecl->field_end();
10172 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010173 QualType FieldType = Context.getBaseElementType(F->getType());
10174 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10175 CXXConstructorDecl *Constructor =
10176 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010177 // If this is a deleted function, add it anyway. This might be conformant
10178 // with the standard. This might not. I'm not sure. It might not matter.
10179 // In particular, the problem is that this function never gets called. It
10180 // might just be ill-formed because this function attempts to refer to
10181 // a deleted function here.
10182 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010183 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010184 }
10185 }
10186
10187 return ExceptSpec;
10188}
10189
10190CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10191 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010192 assert(ClassDecl->needsImplicitMoveConstructor());
10193
Richard Smith8bf22e52012-11-29 01:34:07 +000010194 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10195 if (DSM.isAlreadyBeingDeclared())
10196 return 0;
10197
Sebastian Redl22653ba2011-08-30 19:58:05 +000010198 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10199 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010200
Richard Smithb5800092012-06-10 05:43:50 +000010201 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10202 CXXMoveConstructor,
10203 false);
10204
Sebastian Redl22653ba2011-08-30 19:58:05 +000010205 DeclarationName Name
10206 = Context.DeclarationNames.getCXXConstructorName(
10207 Context.getCanonicalType(ClassType));
10208 SourceLocation ClassLoc = ClassDecl->getLocation();
10209 DeclarationNameInfo NameInfo(Name, ClassLoc);
10210
Richard Smith99005e62013-05-07 03:19:20 +000010211 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010212 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010213 // member of its class.
10214 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010215 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010216 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010217 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010218 MoveConstructor->setAccess(AS_public);
10219 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010220
Richard Smithd3b5c9082012-07-27 04:22:15 +000010221 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010222 FunctionProtoType::ExtProtoInfo EPI =
10223 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010224 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010225 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010226
Sebastian Redl22653ba2011-08-30 19:58:05 +000010227 // Add the parameter to the constructor.
10228 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10229 ClassLoc, ClassLoc,
10230 /*IdentifierInfo=*/0,
10231 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010232 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010233 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010234
Richard Smith6b02d462012-12-08 08:32:28 +000010235 MoveConstructor->setTrivial(
10236 ClassDecl->needsOverloadResolutionForMoveConstructor()
10237 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10238 : ClassDecl->hasTrivialMoveConstructor());
10239
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010240 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010241 ClassDecl->setImplicitMoveConstructorIsDeleted();
10242 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010243 }
10244
10245 // Note that we have declared this constructor.
10246 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10247
10248 if (Scope *S = getScopeForContext(ClassDecl))
10249 PushOnScopeChains(MoveConstructor, S, false);
10250 ClassDecl->addDecl(MoveConstructor);
10251
10252 return MoveConstructor;
10253}
10254
10255void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10256 CXXConstructorDecl *MoveConstructor) {
10257 assert((MoveConstructor->isDefaulted() &&
10258 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010259 !MoveConstructor->doesThisDeclarationHaveABody() &&
10260 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010261 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10262
10263 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10264 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10265
Eli Friedmaneaf34142012-10-18 20:14:08 +000010266 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010267 DiagnosticErrorTrap Trap(Diags);
10268
David Blaikie3fc2f912013-01-17 05:26:25 +000010269 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010270 Trap.hasErrorOccurred()) {
10271 Diag(CurrentLocation, diag::note_member_synthesized_at)
10272 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10273 MoveConstructor->setInvalidDecl();
10274 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010275 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010276 MoveConstructor->setBody(ActOnCompoundStmt(
10277 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10278 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010279 }
10280
Eli Friedman276dd182013-09-05 00:02:25 +000010281 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010282
10283 if (ASTMutationListener *L = getASTMutationListener()) {
10284 L->CompletedImplicitDefinition(MoveConstructor);
10285 }
10286}
10287
Douglas Gregor74f7d502012-02-15 19:33:52 +000010288bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010289 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010290}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010291
10292void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010293 SourceLocation CurrentLocation,
10294 CXXConversionDecl *Conv) {
10295 CXXRecordDecl *Lambda = Conv->getParent();
10296 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10297 // If we are defining a specialization of a conversion to function-ptr
10298 // cache the deduced template arguments for this specialization
10299 // so that we can use them to retrieve the corresponding call-operator
10300 // and static-invoker.
10301 const TemplateArgumentList *DeducedTemplateArgs = 0;
10302
Douglas Gregor355efbb2012-02-17 03:02:34 +000010303
Faisal Vali571df122013-09-29 08:45:24 +000010304 // Retrieve the corresponding call-operator specialization.
10305 if (Lambda->isGenericLambda()) {
10306 assert(Conv->isFunctionTemplateSpecialization());
10307 FunctionTemplateDecl *CallOpTemplate =
10308 CallOp->getDescribedFunctionTemplate();
10309 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10310 void *InsertPos = 0;
10311 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10312 DeducedTemplateArgs->data(),
10313 DeducedTemplateArgs->size(),
10314 InsertPos);
10315 assert(CallOpSpec &&
10316 "Conversion operator must have a corresponding call operator");
10317 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10318 }
10319 // Mark the call operator referenced (and add to pending instantiations
10320 // if necessary).
10321 // For both the conversion and static-invoker template specializations
10322 // we construct their body's in this function, so no need to add them
10323 // to the PendingInstantiations.
10324 MarkFunctionReferenced(CurrentLocation, CallOp);
10325
Eli Friedmaneaf34142012-10-18 20:14:08 +000010326 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010327 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010328
10329 // Retreive the static invoker...
10330 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10331 // ... and get the corresponding specialization for a generic lambda.
10332 if (Lambda->isGenericLambda()) {
10333 assert(DeducedTemplateArgs &&
10334 "Must have deduced template arguments from Conversion Operator");
10335 FunctionTemplateDecl *InvokeTemplate =
10336 Invoker->getDescribedFunctionTemplate();
10337 void *InsertPos = 0;
10338 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10339 DeducedTemplateArgs->data(),
10340 DeducedTemplateArgs->size(),
10341 InsertPos);
10342 assert(InvokeSpec &&
10343 "Must have a corresponding static invoker specialization");
10344 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10345 }
10346 // Construct the body of the conversion function { return __invoke; }.
10347 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10348 VK_LValue, Conv->getLocation()).take();
10349 assert(FunctionRef && "Can't refer to __invoke function?");
10350 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10351 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10352 Conv->getLocation(),
10353 Conv->getLocation()));
10354
10355 Conv->markUsed(Context);
10356 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010357
Faisal Vali571df122013-09-29 08:45:24 +000010358 // Fill in the __invoke function with a dummy implementation. IR generation
10359 // will fill in the actual details.
10360 Invoker->markUsed(Context);
10361 Invoker->setReferenced();
10362 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10363
Douglas Gregord3b672c2012-02-16 01:06:16 +000010364 if (ASTMutationListener *L = getASTMutationListener()) {
10365 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010366 L->CompletedImplicitDefinition(Invoker);
10367 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010368}
10369
Faisal Vali571df122013-09-29 08:45:24 +000010370
10371
Douglas Gregord3b672c2012-02-16 01:06:16 +000010372void Sema::DefineImplicitLambdaToBlockPointerConversion(
10373 SourceLocation CurrentLocation,
10374 CXXConversionDecl *Conv)
10375{
Faisal Vali850da1a2013-09-29 17:08:32 +000010376 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010377
Eli Friedman276dd182013-09-05 00:02:25 +000010378 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010379
Eli Friedmaneaf34142012-10-18 20:14:08 +000010380 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010381 DiagnosticErrorTrap Trap(Diags);
10382
Douglas Gregored90df32012-02-22 05:02:47 +000010383 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010384 Expr *This = ActOnCXXThis(CurrentLocation).take();
10385 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010386
Eli Friedman98b01ed2012-03-01 04:01:32 +000010387 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10388 Conv->getLocation(),
10389 Conv, DerefThis);
10390
10391 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10392 // behavior. Note that only the general conversion function does this
10393 // (since it's unusable otherwise); in the case where we inline the
10394 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010395 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010396 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10397 CK_CopyAndAutoreleaseBlockObject,
10398 BuildBlock.get(), 0, VK_RValue);
10399
10400 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010401 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010402 Conv->setInvalidDecl();
10403 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010404 }
Douglas Gregored90df32012-02-22 05:02:47 +000010405
Douglas Gregored90df32012-02-22 05:02:47 +000010406 // Create the return statement that returns the block from the conversion
10407 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010408 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010409 if (Return.isInvalid()) {
10410 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10411 Conv->setInvalidDecl();
10412 return;
10413 }
10414
10415 // Set the body of the conversion function.
10416 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010417 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010418 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010419 Conv->getLocation()));
10420
Douglas Gregored90df32012-02-22 05:02:47 +000010421 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010422 if (ASTMutationListener *L = getASTMutationListener()) {
10423 L->CompletedImplicitDefinition(Conv);
10424 }
10425}
10426
Douglas Gregord2f70072012-03-10 06:53:13 +000010427/// \brief Determine whether the given list arguments contains exactly one
10428/// "real" (non-default) argument.
10429static bool hasOneRealArgument(MultiExprArg Args) {
10430 switch (Args.size()) {
10431 case 0:
10432 return false;
10433
10434 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010435 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010436 return false;
10437
10438 // fall through
10439 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010440 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010441 }
10442
10443 return false;
10444}
10445
John McCalldadc5752010-08-24 06:29:42 +000010446ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010447Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010448 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010449 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010450 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010451 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010452 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010453 unsigned ConstructKind,
10454 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010455 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010456
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010457 // C++0x [class.copy]p34:
10458 // When certain criteria are met, an implementation is allowed to
10459 // omit the copy/move construction of a class object, even if the
10460 // copy/move constructor and/or destructor for the object have
10461 // side effects. [...]
10462 // - when a temporary class object that has not been bound to a
10463 // reference (12.2) would be copied/moved to a class object
10464 // with the same cv-unqualified type, the copy/move operation
10465 // can be omitted by constructing the temporary object
10466 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010467 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010468 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010469 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010470 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010471 }
Mike Stump11289f42009-09-09 15:08:12 +000010472
10473 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010474 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010475 IsListInitialization, RequiresZeroInit,
10476 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010477}
10478
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010479/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10480/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010481ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010482Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10483 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010484 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010485 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010486 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010487 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010488 unsigned ConstructKind,
10489 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010490 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010491 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010492 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010493 HadMultipleCandidates,
10494 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010495 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10496 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010497}
10498
John McCall03c48482010-02-02 09:10:11 +000010499void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010500 if (VD->isInvalidDecl()) return;
10501
John McCall03c48482010-02-02 09:10:11 +000010502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010503 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010504 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010505 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010506
Chandler Carruth86d17d32011-03-27 21:26:48 +000010507 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010508 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010509 CheckDestructorAccess(VD->getLocation(), Destructor,
10510 PDiag(diag::err_access_dtor_var)
10511 << VD->getDeclName()
10512 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010513 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010514
Chandler Carruth86d17d32011-03-27 21:26:48 +000010515 if (!VD->hasGlobalStorage()) return;
10516
10517 // Emit warning for non-trivial dtor in global scope (a real global,
10518 // class-static, function-static).
10519 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10520
10521 // TODO: this should be re-enabled for static locals by !CXAAtExit
10522 if (!VD->isStaticLocal())
10523 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010524}
10525
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010526/// \brief Given a constructor and the set of arguments provided for the
10527/// constructor, convert the arguments and add any required default arguments
10528/// to form a proper call to this constructor.
10529///
10530/// \returns true if an error occurred, false otherwise.
10531bool
10532Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10533 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010534 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010535 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010536 bool AllowExplicit,
10537 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010538 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10539 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010540 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010541
10542 const FunctionProtoType *Proto
10543 = Constructor->getType()->getAs<FunctionProtoType>();
10544 assert(Proto && "Constructor without a prototype?");
10545 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010546
10547 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010548 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010549 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010550 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010551 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010552
10553 VariadicCallType CallType =
10554 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010555 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010556 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010557 Proto, 0,
10558 llvm::makeArrayRef(Args, NumArgs),
10559 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010560 CallType, AllowExplicit,
10561 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010562 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010563
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010564 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010565
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010566 CheckConstructorCall(Constructor,
10567 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10568 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010569 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010570
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010571 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010572}
10573
Anders Carlssone363c8e2009-12-12 00:32:00 +000010574static inline bool
10575CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10576 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010577 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010578 if (isa<NamespaceDecl>(DC)) {
10579 return SemaRef.Diag(FnDecl->getLocation(),
10580 diag::err_operator_new_delete_declared_in_namespace)
10581 << FnDecl->getDeclName();
10582 }
10583
10584 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010585 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010586 return SemaRef.Diag(FnDecl->getLocation(),
10587 diag::err_operator_new_delete_declared_static)
10588 << FnDecl->getDeclName();
10589 }
10590
Anders Carlsson60659a82009-12-12 02:43:16 +000010591 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010592}
10593
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010594static inline bool
10595CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10596 CanQualType ExpectedResultType,
10597 CanQualType ExpectedFirstParamType,
10598 unsigned DependentParamTypeDiag,
10599 unsigned InvalidParamTypeDiag) {
10600 QualType ResultType =
10601 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10602
10603 // Check that the result type is not dependent.
10604 if (ResultType->isDependentType())
10605 return SemaRef.Diag(FnDecl->getLocation(),
10606 diag::err_operator_new_delete_dependent_result_type)
10607 << FnDecl->getDeclName() << ExpectedResultType;
10608
10609 // Check that the result type is what we expect.
10610 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10611 return SemaRef.Diag(FnDecl->getLocation(),
10612 diag::err_operator_new_delete_invalid_result_type)
10613 << FnDecl->getDeclName() << ExpectedResultType;
10614
10615 // A function template must have at least 2 parameters.
10616 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10617 return SemaRef.Diag(FnDecl->getLocation(),
10618 diag::err_operator_new_delete_template_too_few_parameters)
10619 << FnDecl->getDeclName();
10620
10621 // The function decl must have at least 1 parameter.
10622 if (FnDecl->getNumParams() == 0)
10623 return SemaRef.Diag(FnDecl->getLocation(),
10624 diag::err_operator_new_delete_too_few_parameters)
10625 << FnDecl->getDeclName();
10626
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010627 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010628 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10629 if (FirstParamType->isDependentType())
10630 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10631 << FnDecl->getDeclName() << ExpectedFirstParamType;
10632
10633 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010634 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010635 ExpectedFirstParamType)
10636 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10637 << FnDecl->getDeclName() << ExpectedFirstParamType;
10638
10639 return false;
10640}
10641
Anders Carlsson12308f42009-12-11 23:23:22 +000010642static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010643CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010644 // C++ [basic.stc.dynamic.allocation]p1:
10645 // A program is ill-formed if an allocation function is declared in a
10646 // namespace scope other than global scope or declared static in global
10647 // scope.
10648 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10649 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010650
10651 CanQualType SizeTy =
10652 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10653
10654 // C++ [basic.stc.dynamic.allocation]p1:
10655 // The return type shall be void*. The first parameter shall have type
10656 // std::size_t.
10657 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10658 SizeTy,
10659 diag::err_operator_new_dependent_param_type,
10660 diag::err_operator_new_param_type))
10661 return true;
10662
10663 // C++ [basic.stc.dynamic.allocation]p1:
10664 // The first parameter shall not have an associated default argument.
10665 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010666 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010667 diag::err_operator_new_default_arg)
10668 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10669
10670 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010671}
10672
10673static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010674CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010675 // C++ [basic.stc.dynamic.deallocation]p1:
10676 // A program is ill-formed if deallocation functions are declared in a
10677 // namespace scope other than global scope or declared static in global
10678 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010679 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10680 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010681
10682 // C++ [basic.stc.dynamic.deallocation]p2:
10683 // Each deallocation function shall return void and its first parameter
10684 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010685 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10686 SemaRef.Context.VoidPtrTy,
10687 diag::err_operator_delete_dependent_param_type,
10688 diag::err_operator_delete_param_type))
10689 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010690
Anders Carlsson12308f42009-12-11 23:23:22 +000010691 return false;
10692}
10693
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010694/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10695/// of this overloaded operator is well-formed. If so, returns false;
10696/// otherwise, emits appropriate diagnostics and returns true.
10697bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010698 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010699 "Expected an overloaded operator declaration");
10700
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010701 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10702
Mike Stump11289f42009-09-09 15:08:12 +000010703 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010704 // The allocation and deallocation functions, operator new,
10705 // operator new[], operator delete and operator delete[], are
10706 // described completely in 3.7.3. The attributes and restrictions
10707 // found in the rest of this subclause do not apply to them unless
10708 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010709 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010710 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010711
Anders Carlsson22f443f2009-12-12 00:26:23 +000010712 if (Op == OO_New || Op == OO_Array_New)
10713 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010714
10715 // C++ [over.oper]p6:
10716 // An operator function shall either be a non-static member
10717 // function or be a non-member function and have at least one
10718 // parameter whose type is a class, a reference to a class, an
10719 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010720 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10721 if (MethodDecl->isStatic())
10722 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010723 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010724 } else {
10725 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +000010726 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10727 ParamEnd = FnDecl->param_end();
10728 Param != ParamEnd; ++Param) {
10729 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010730 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10731 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010732 ClassOrEnumParam = true;
10733 break;
10734 }
10735 }
10736
Douglas Gregord69246b2008-11-17 16:14:12 +000010737 if (!ClassOrEnumParam)
10738 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010739 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010740 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010741 }
10742
10743 // C++ [over.oper]p8:
10744 // An operator function cannot have default arguments (8.3.6),
10745 // except where explicitly stated below.
10746 //
Mike Stump11289f42009-09-09 15:08:12 +000010747 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010748 // (C++ [over.call]p1).
10749 if (Op != OO_Call) {
10750 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10751 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010752 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +000010753 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010754 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010755 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010756 }
10757 }
10758
Douglas Gregor6cf08062008-11-10 13:38:07 +000010759 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10760 { false, false, false }
10761#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10762 , { Unary, Binary, MemberOnly }
10763#include "clang/Basic/OperatorKinds.def"
10764 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010765
Douglas Gregor6cf08062008-11-10 13:38:07 +000010766 bool CanBeUnaryOperator = OperatorUses[Op][0];
10767 bool CanBeBinaryOperator = OperatorUses[Op][1];
10768 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010769
10770 // C++ [over.oper]p8:
10771 // [...] Operator functions cannot have more or fewer parameters
10772 // than the number required for the corresponding operator, as
10773 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010774 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010775 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010776 if (Op != OO_Call &&
10777 ((NumParams == 1 && !CanBeUnaryOperator) ||
10778 (NumParams == 2 && !CanBeBinaryOperator) ||
10779 (NumParams < 1) || (NumParams > 2))) {
10780 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010781 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010782 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010783 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010784 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010785 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010786 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010787 assert(CanBeBinaryOperator &&
10788 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010789 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010790 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010791
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010792 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010793 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010794 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010795
Douglas Gregord69246b2008-11-17 16:14:12 +000010796 // Overloaded operators other than operator() cannot be variadic.
10797 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010798 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010799 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010800 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010801 }
10802
10803 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010804 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10805 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010806 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010807 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010808 }
10809
10810 // C++ [over.inc]p1:
10811 // The user-defined function called operator++ implements the
10812 // prefix and postfix ++ operator. If this function is a member
10813 // function with no parameters, or a non-member function with one
10814 // parameter of class or enumeration type, it defines the prefix
10815 // increment operator ++ for objects of that type. If the function
10816 // is a member function with one parameter (which shall be of type
10817 // int) or a non-member function with two parameters (the second
10818 // of which shall be of type int), it defines the postfix
10819 // increment operator ++ for objects of that type.
10820 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10821 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10822 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +000010823 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010824 ParamIsInt = BT->getKind() == BuiltinType::Int;
10825
Chris Lattner2b786902008-11-21 07:50:02 +000010826 if (!ParamIsInt)
10827 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010828 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010829 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010830 }
10831
Douglas Gregord69246b2008-11-17 16:14:12 +000010832 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010833}
Chris Lattner3b024a32008-12-17 07:09:26 +000010834
Alexis Huntc88db062010-01-13 09:01:02 +000010835/// CheckLiteralOperatorDeclaration - Check whether the declaration
10836/// of this literal operator function is well-formed. If so, returns
10837/// false; otherwise, emits appropriate diagnostics and returns true.
10838bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010839 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010840 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10841 << FnDecl->getDeclName();
10842 return true;
10843 }
10844
Richard Smith72eebee2012-03-04 09:41:16 +000010845 if (FnDecl->isExternC()) {
10846 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10847 return true;
10848 }
10849
Alexis Huntc88db062010-01-13 09:01:02 +000010850 bool Valid = false;
10851
Richard Smithbcc22fc2012-03-09 08:00:36 +000010852 // This might be the definition of a literal operator template.
10853 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10854 // This might be a specialization of a literal operator template.
10855 if (!TpDecl)
10856 TpDecl = FnDecl->getPrimaryTemplate();
10857
Richard Smithb8b41d32013-10-07 19:57:58 +000010858 // template <char...> type operator "" name() and
10859 // template <class T, T...> type operator "" name() are the only valid
10860 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010861 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010862 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010863 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010864 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10865 if (Params->size() == 1) {
10866 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010867 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010868
Alexis Hunt7dd26172010-04-07 23:11:06 +000010869 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010870 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10871 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10872 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010873 } else if (Params->size() == 2) {
10874 TemplateTypeParmDecl *PmType =
10875 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10876 NonTypeTemplateParmDecl *PmArgs =
10877 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10878
10879 // The second template parameter must be a parameter pack with the
10880 // first template parameter as its type.
10881 if (PmType && PmArgs &&
10882 !PmType->isTemplateParameterPack() &&
10883 PmArgs->isTemplateParameterPack()) {
10884 const TemplateTypeParmType *TArgs =
10885 PmArgs->getType()->getAs<TemplateTypeParmType>();
10886 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10887 TArgs->getIndex() == PmType->getIndex()) {
10888 Valid = true;
10889 if (ActiveTemplateInstantiations.empty())
10890 Diag(FnDecl->getLocation(),
10891 diag::ext_string_literal_operator_template);
10892 }
10893 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010894 }
10895 }
Richard Smith72eebee2012-03-04 09:41:16 +000010896 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010897 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010898 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10899
Richard Smith72eebee2012-03-04 09:41:16 +000010900 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010901
Alexis Hunt079a6f72010-04-07 22:57:35 +000010902 // unsigned long long int, long double, and any character type are allowed
10903 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010904 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10905 Context.hasSameType(T, Context.LongDoubleTy) ||
10906 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010907 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010908 Context.hasSameType(T, Context.Char16Ty) ||
10909 Context.hasSameType(T, Context.Char32Ty)) {
10910 if (++Param == FnDecl->param_end())
10911 Valid = true;
10912 goto FinishedParams;
10913 }
10914
Alexis Hunt079a6f72010-04-07 22:57:35 +000010915 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010916 const PointerType *PT = T->getAs<PointerType>();
10917 if (!PT)
10918 goto FinishedParams;
10919 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010920 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010921 goto FinishedParams;
10922 T = T.getUnqualifiedType();
10923
10924 // Move on to the second parameter;
10925 ++Param;
10926
10927 // If there is no second parameter, the first must be a const char *
10928 if (Param == FnDecl->param_end()) {
10929 if (Context.hasSameType(T, Context.CharTy))
10930 Valid = true;
10931 goto FinishedParams;
10932 }
10933
10934 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10935 // are allowed as the first parameter to a two-parameter function
10936 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010937 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010938 Context.hasSameType(T, Context.Char16Ty) ||
10939 Context.hasSameType(T, Context.Char32Ty)))
10940 goto FinishedParams;
10941
10942 // The second and final parameter must be an std::size_t
10943 T = (*Param)->getType().getUnqualifiedType();
10944 if (Context.hasSameType(T, Context.getSizeType()) &&
10945 ++Param == FnDecl->param_end())
10946 Valid = true;
10947 }
10948
10949 // FIXME: This diagnostic is absolutely terrible.
10950FinishedParams:
10951 if (!Valid) {
10952 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10953 << FnDecl->getDeclName();
10954 return true;
10955 }
10956
Richard Smith768cecc2012-03-09 08:16:22 +000010957 // A parameter-declaration-clause containing a default argument is not
10958 // equivalent to any of the permitted forms.
10959 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10960 ParamEnd = FnDecl->param_end();
10961 Param != ParamEnd; ++Param) {
10962 if ((*Param)->hasDefaultArg()) {
10963 Diag((*Param)->getDefaultArgRange().getBegin(),
10964 diag::err_literal_operator_default_argument)
10965 << (*Param)->getDefaultArgRange();
10966 break;
10967 }
10968 }
10969
Richard Smith0df56f42012-03-08 02:39:21 +000010970 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000010971 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10972 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000010973 // C++11 [usrlit.suffix]p1:
10974 // Literal suffix identifiers that do not start with an underscore
10975 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000010976 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10977 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000010978 }
Richard Smith0df56f42012-03-08 02:39:21 +000010979
Alexis Huntc88db062010-01-13 09:01:02 +000010980 return false;
10981}
10982
Douglas Gregor07665a62009-01-05 19:45:36 +000010983/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10984/// linkage specification, including the language and (if present)
10985/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10986/// the location of the language string literal, which is provided
10987/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10988/// the '{' brace. Otherwise, this linkage specification does not
10989/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000010990Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10991 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010992 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +000010993 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +000010994 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +000010995 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +000010996 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +000010997 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +000010998 Language = LinkageSpecDecl::lang_cxx;
10999 else {
Douglas Gregor07665a62009-01-05 19:45:36 +000011000 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +000011001 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011002 }
Mike Stump11289f42009-09-09 15:08:12 +000011003
Chris Lattner438e5012008-12-17 07:13:27 +000011004 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011005
Douglas Gregor07665a62009-01-05 19:45:36 +000011006 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011007 ExternLoc, LangLoc, Language,
11008 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011009 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011010 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011011 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011012}
11013
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011014/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011015/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11016/// valid, it's the position of the closing '}' brace in a linkage
11017/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011018Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011019 Decl *LinkageSpec,
11020 SourceLocation RBraceLoc) {
11021 if (LinkageSpec) {
11022 if (RBraceLoc.isValid()) {
11023 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11024 LSDecl->setRBraceLoc(RBraceLoc);
11025 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011026 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011027 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011028 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011029}
11030
Michael Han84324352013-02-22 17:15:32 +000011031Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11032 AttributeList *AttrList,
11033 SourceLocation SemiLoc) {
11034 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11035 // Attribute declarations appertain to empty declaration so we handle
11036 // them here.
11037 if (AttrList)
11038 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011039
Michael Han84324352013-02-22 17:15:32 +000011040 CurContext->addDecl(ED);
11041 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011042}
11043
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011044/// \brief Perform semantic analysis for the variable declaration that
11045/// occurs within a C++ catch clause, returning the newly-created
11046/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011047VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011048 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011049 SourceLocation StartLoc,
11050 SourceLocation Loc,
11051 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011052 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011053 QualType ExDeclType = TInfo->getType();
11054
Sebastian Redl54c04d42008-12-22 19:15:10 +000011055 // Arrays and functions decay.
11056 if (ExDeclType->isArrayType())
11057 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11058 else if (ExDeclType->isFunctionType())
11059 ExDeclType = Context.getPointerType(ExDeclType);
11060
11061 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11062 // The exception-declaration shall not denote a pointer or reference to an
11063 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011064 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011065 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011066 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011067 Invalid = true;
11068 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011069
Sebastian Redl54c04d42008-12-22 19:15:10 +000011070 QualType BaseType = ExDeclType;
11071 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011072 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011073 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011074 BaseType = Ptr->getPointeeType();
11075 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011076 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011077 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011078 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011079 BaseType = Ref->getPointeeType();
11080 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011081 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011082 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011083 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011084 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011085 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011086
Mike Stump11289f42009-09-09 15:08:12 +000011087 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011088 RequireNonAbstractType(Loc, ExDeclType,
11089 diag::err_abstract_type_in_decl,
11090 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011091 Invalid = true;
11092
John McCall2ca705e2010-07-24 00:37:23 +000011093 // Only the non-fragile NeXT runtime currently supports C++ catches
11094 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011095 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011096 QualType T = ExDeclType;
11097 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11098 T = RT->getPointeeType();
11099
11100 if (T->isObjCObjectType()) {
11101 Diag(Loc, diag::err_objc_object_catch);
11102 Invalid = true;
11103 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011104 // FIXME: should this be a test for macosx-fragile specifically?
11105 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011106 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011107 }
11108 }
11109
Abramo Bagnaradff19302011-03-08 08:55:46 +000011110 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011111 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011112 ExDecl->setExceptionVariable(true);
11113
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011114 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011115 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011116 Invalid = true;
11117
Douglas Gregor750734c2011-07-06 18:14:43 +000011118 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011119 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011120 // Insulate this from anything else we might currently be parsing.
11121 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11122
Douglas Gregor6de584c2010-03-05 23:38:39 +000011123 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011124 // The object declared in an exception-declaration or, if the
11125 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011126 // copy-initialized (8.5) from the exception object. [...]
11127 // The object is destroyed when the handler exits, after the destruction
11128 // of any automatic objects initialized within the handler.
11129 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011130 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011131 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011132 QualType initType = ExDeclType;
11133
11134 InitializedEntity entity =
11135 InitializedEntity::InitializeVariable(ExDecl);
11136 InitializationKind initKind =
11137 InitializationKind::CreateCopy(Loc, SourceLocation());
11138
11139 Expr *opaqueValue =
11140 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011141 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11142 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011143 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011144 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011145 else {
11146 // If the constructor used was non-trivial, set this as the
11147 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011148 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011149 if (!construct->getConstructor()->isTrivial()) {
11150 Expr *init = MaybeCreateExprWithCleanups(construct);
11151 ExDecl->setInit(init);
11152 }
11153
11154 // And make sure it's destructable.
11155 FinalizeVarWithDestructor(ExDecl, recordType);
11156 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011157 }
11158 }
11159
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011160 if (Invalid)
11161 ExDecl->setInvalidDecl();
11162
11163 return ExDecl;
11164}
11165
11166/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11167/// handler.
John McCall48871652010-08-21 09:40:31 +000011168Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011169 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011170 bool Invalid = D.isInvalidType();
11171
11172 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011173 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11174 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011175 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11176 D.getIdentifierLoc());
11177 Invalid = true;
11178 }
11179
Sebastian Redl54c04d42008-12-22 19:15:10 +000011180 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011181 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011182 LookupOrdinaryName,
11183 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011184 // The scope should be freshly made just for us. There is just no way
11185 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011186 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011187 if (PrevDecl->isTemplateParameter()) {
11188 // Maybe we will complain about the shadowed template parameter.
11189 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011190 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011191 }
11192 }
11193
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011194 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011195 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11196 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011197 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011198 }
11199
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011200 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011201 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011202 D.getIdentifierLoc(),
11203 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011204 if (Invalid)
11205 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011206
Sebastian Redl54c04d42008-12-22 19:15:10 +000011207 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011208 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011209 PushOnScopeChains(ExDecl, S);
11210 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011211 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011212
Douglas Gregor758a8692009-06-17 21:51:59 +000011213 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011214 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011215}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011216
Abramo Bagnaraea947882011-03-08 16:41:52 +000011217Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011218 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011219 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011220 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011221 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011222
Richard Smithded9c2e2012-07-11 22:37:56 +000011223 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11224 return 0;
11225
11226 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11227 AssertMessage, RParenLoc, false);
11228}
11229
11230Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11231 Expr *AssertExpr,
11232 StringLiteral *AssertMessage,
11233 SourceLocation RParenLoc,
11234 bool Failed) {
11235 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11236 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011237 // In a static_assert-declaration, the constant-expression shall be a
11238 // constant expression that can be contextually converted to bool.
11239 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11240 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011241 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011242
Richard Smith902ca212011-12-14 23:32:26 +000011243 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011244 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011245 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011246 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011247 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011248
Richard Smithded9c2e2012-07-11 22:37:56 +000011249 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011250 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011251 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011252 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011253 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011254 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011255 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011256 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011257 }
Mike Stump11289f42009-09-09 15:08:12 +000011258
Abramo Bagnaraea947882011-03-08 16:41:52 +000011259 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011260 AssertExpr, AssertMessage, RParenLoc,
11261 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011262
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011263 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011264 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011265}
Sebastian Redlf769df52009-03-24 22:27:57 +000011266
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011267/// \brief Perform semantic analysis of the given friend type declaration.
11268///
11269/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011270FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011271 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011272 TypeSourceInfo *TSInfo) {
11273 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11274
11275 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011276 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011277
Richard Smithc8239732011-10-18 21:39:00 +000011278 // C++03 [class.friend]p2:
11279 // An elaborated-type-specifier shall be used in a friend declaration
11280 // for a class.*
11281 //
11282 // * The class-key of the elaborated-type-specifier is required.
11283 if (!ActiveTemplateInstantiations.empty()) {
11284 // Do not complain about the form of friend template types during
11285 // template instantiation; we will already have complained when the
11286 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011287 } else {
11288 if (!T->isElaboratedTypeSpecifier()) {
11289 // If we evaluated the type to a record type, suggest putting
11290 // a tag in front.
11291 if (const RecordType *RT = T->getAs<RecordType>()) {
11292 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011293
Nick Lewycky36722d22013-02-06 05:59:33 +000011294 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011295
Nick Lewycky36722d22013-02-06 05:59:33 +000011296 Diag(TypeRange.getBegin(),
11297 getLangOpts().CPlusPlus11 ?
11298 diag::warn_cxx98_compat_unelaborated_friend_type :
11299 diag::ext_unelaborated_friend_type)
11300 << (unsigned) RD->getTagKind()
11301 << T
11302 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11303 InsertionText);
11304 } else {
11305 Diag(FriendLoc,
11306 getLangOpts().CPlusPlus11 ?
11307 diag::warn_cxx98_compat_nonclass_type_friend :
11308 diag::ext_nonclass_type_friend)
11309 << T
11310 << TypeRange;
11311 }
11312 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011313 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011314 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011315 diag::warn_cxx98_compat_enum_friend :
11316 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011317 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011318 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011319 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011320
Nick Lewycky36722d22013-02-06 05:59:33 +000011321 // C++11 [class.friend]p3:
11322 // A friend declaration that does not declare a function shall have one
11323 // of the following forms:
11324 // friend elaborated-type-specifier ;
11325 // friend simple-type-specifier ;
11326 // friend typename-specifier ;
11327 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11328 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11329 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011330
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011331 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011332 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011333 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011334 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011335}
11336
John McCallace48cd2010-10-19 01:40:49 +000011337/// Handle a friend tag declaration where the scope specifier was
11338/// templated.
11339Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11340 unsigned TagSpec, SourceLocation TagLoc,
11341 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011342 IdentifierInfo *Name,
11343 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011344 AttributeList *Attr,
11345 MultiTemplateParamsArg TempParamLists) {
11346 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11347
11348 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011349 bool Invalid = false;
11350
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011351 if (TemplateParameterList *TemplateParams =
11352 MatchTemplateParametersToScopeSpecifier(
11353 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11354 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011355 if (TemplateParams->size() > 0) {
11356 // This is a declaration of a class template.
11357 if (Invalid)
11358 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011359
Eric Christopher6f228b52011-07-21 05:34:24 +000011360 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11361 SS, Name, NameLoc, Attr,
11362 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011363 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011364 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011365 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011366 } else {
11367 // The "template<>" header is extraneous.
11368 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11369 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11370 isExplicitSpecialization = true;
11371 }
11372 }
11373
11374 if (Invalid) return 0;
11375
John McCallace48cd2010-10-19 01:40:49 +000011376 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011377 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011378 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011379 isAllExplicitSpecializations = false;
11380 break;
11381 }
11382 }
11383
11384 // FIXME: don't ignore attributes.
11385
11386 // If it's explicit specializations all the way down, just forget
11387 // about the template header and build an appropriate non-templated
11388 // friend. TODO: for source fidelity, remember the headers.
11389 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011390 if (SS.isEmpty()) {
11391 bool Owned = false;
11392 bool IsDependent = false;
11393 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11394 Attr, AS_public,
11395 /*ModulePrivateLoc=*/SourceLocation(),
11396 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011397 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011398 /*ScopedEnumUsesClassTag=*/false,
11399 /*UnderlyingType=*/TypeResult());
11400 }
11401
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011402 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011403 ElaboratedTypeKeyword Keyword
11404 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011405 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011406 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011407 if (T.isNull())
11408 return 0;
11409
11410 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11411 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011412 DependentNameTypeLoc TL =
11413 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011414 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011415 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011416 TL.setNameLoc(NameLoc);
11417 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011418 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011419 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011420 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011421 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011422 }
11423
11424 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011425 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011426 Friend->setAccess(AS_public);
11427 CurContext->addDecl(Friend);
11428 return Friend;
11429 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011430
11431 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11432
11433
John McCallace48cd2010-10-19 01:40:49 +000011434
11435 // Handle the case of a templated-scope friend class. e.g.
11436 // template <class T> class A<T>::B;
11437 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011438 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11439 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011440 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11441 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11442 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011443 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011444 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011445 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011446 TL.setNameLoc(NameLoc);
11447
11448 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011449 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011450 Friend->setAccess(AS_public);
11451 Friend->setUnsupportedFriend(true);
11452 CurContext->addDecl(Friend);
11453 return Friend;
11454}
11455
11456
John McCall11083da2009-09-16 22:47:08 +000011457/// Handle a friend type declaration. This works in tandem with
11458/// ActOnTag.
11459///
11460/// Notes on friend class templates:
11461///
11462/// We generally treat friend class declarations as if they were
11463/// declaring a class. So, for example, the elaborated type specifier
11464/// in a friend declaration is required to obey the restrictions of a
11465/// class-head (i.e. no typedefs in the scope chain), template
11466/// parameters are required to match up with simple template-ids, &c.
11467/// However, unlike when declaring a template specialization, it's
11468/// okay to refer to a template specialization without an empty
11469/// template parameter declaration, e.g.
11470/// friend class A<T>::B<unsigned>;
11471/// We permit this as a special case; if there are any template
11472/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011473/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011474Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011475 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011476 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011477
11478 assert(DS.isFriendSpecified());
11479 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11480
John McCall11083da2009-09-16 22:47:08 +000011481 // Try to convert the decl specifier to a type. This works for
11482 // friend templates because ActOnTag never produces a ClassTemplateDecl
11483 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011484 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011485 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11486 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011487 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011488 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011489
Douglas Gregor6c110f32010-12-16 01:14:37 +000011490 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11491 return 0;
11492
John McCall11083da2009-09-16 22:47:08 +000011493 // This is definitely an error in C++98. It's probably meant to
11494 // be forbidden in C++0x, too, but the specification is just
11495 // poorly written.
11496 //
11497 // The problem is with declarations like the following:
11498 // template <T> friend A<T>::foo;
11499 // where deciding whether a class C is a friend or not now hinges
11500 // on whether there exists an instantiation of A that causes
11501 // 'foo' to equal C. There are restrictions on class-heads
11502 // (which we declare (by fiat) elaborated friend declarations to
11503 // be) that makes this tractable.
11504 //
11505 // FIXME: handle "template <> friend class A<T>;", which
11506 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011507 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011508 Diag(Loc, diag::err_tagless_friend_type_template)
11509 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011510 return 0;
John McCall11083da2009-09-16 22:47:08 +000011511 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011512
John McCallaa74a0c2009-08-28 07:59:38 +000011513 // C++98 [class.friend]p1: A friend of a class is a function
11514 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011515 // This is fixed in DR77, which just barely didn't make the C++03
11516 // deadline. It's also a very silly restriction that seriously
11517 // affects inner classes and which nobody else seems to implement;
11518 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011519 //
11520 // But note that we could warn about it: it's always useless to
11521 // friend one of your own members (it's not, however, worthless to
11522 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011523
John McCall11083da2009-09-16 22:47:08 +000011524 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011525 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011526 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011527 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011528 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011529 TSI,
John McCall11083da2009-09-16 22:47:08 +000011530 DS.getFriendSpecLoc());
11531 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011532 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011533
11534 if (!D)
John McCall48871652010-08-21 09:40:31 +000011535 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011536
John McCall11083da2009-09-16 22:47:08 +000011537 D->setAccess(AS_public);
11538 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011539
John McCall48871652010-08-21 09:40:31 +000011540 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011541}
11542
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011543NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11544 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011545 const DeclSpec &DS = D.getDeclSpec();
11546
11547 assert(DS.isFriendSpecified());
11548 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11549
11550 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011551 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011552
11553 // C++ [class.friend]p1
11554 // A friend of a class is a function or class....
11555 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011556 // It *doesn't* see through dependent types, which is correct
11557 // according to [temp.arg.type]p3:
11558 // If a declaration acquires a function type through a
11559 // type dependent on a template-parameter and this causes
11560 // a declaration that does not use the syntactic form of a
11561 // function declarator to have a function type, the program
11562 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011563 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011564 Diag(Loc, diag::err_unexpected_friend);
11565
11566 // It might be worthwhile to try to recover by creating an
11567 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011568 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011569 }
11570
11571 // C++ [namespace.memdef]p3
11572 // - If a friend declaration in a non-local class first declares a
11573 // class or function, the friend class or function is a member
11574 // of the innermost enclosing namespace.
11575 // - The name of the friend is not found by simple name lookup
11576 // until a matching declaration is provided in that namespace
11577 // scope (either before or after the class declaration granting
11578 // friendship).
11579 // - If a friend function is called, its name may be found by the
11580 // name lookup that considers functions from namespaces and
11581 // classes associated with the types of the function arguments.
11582 // - When looking for a prior declaration of a class or a function
11583 // declared as a friend, scopes outside the innermost enclosing
11584 // namespace scope are not considered.
11585
John McCallde3fd222010-10-12 23:13:28 +000011586 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011587 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11588 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011589 assert(Name);
11590
Douglas Gregor6c110f32010-12-16 01:14:37 +000011591 // Check for unexpanded parameter packs.
11592 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11593 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11594 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11595 return 0;
11596
John McCall07e91c02009-08-06 02:15:43 +000011597 // The context we found the declaration in, or in which we should
11598 // create the declaration.
11599 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011600 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011601 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011602 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011603
Richard Smith114394f2013-08-09 04:35:01 +000011604 // There are five cases here.
11605 // - There's no scope specifier and we're in a local class. Only look
11606 // for functions declared in the immediately-enclosing block scope.
11607 // We recover from invalid scope qualifiers as if they just weren't there.
11608 FunctionDecl *FunctionContainingLocalClass = 0;
11609 if ((SS.isInvalid() || !SS.isSet()) &&
11610 (FunctionContainingLocalClass =
11611 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11612 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011613 // If a friend declaration appears in a local class and the name
11614 // specified is an unqualified name, a prior declaration is
11615 // looked up without considering scopes that are outside the
11616 // innermost enclosing non-class scope. For a friend function
11617 // declaration, if there is no prior declaration, the program is
11618 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011619
11620 // Find the innermost enclosing non-class scope. This is the block
11621 // scope containing the local class definition (or for a nested class,
11622 // the outer local class).
11623 DCScope = S->getFnParent();
11624
11625 // Look up the function name in the scope.
11626 Previous.clear(LookupLocalFriendName);
11627 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11628
11629 if (!Previous.empty()) {
11630 // All possible previous declarations must have the same context:
11631 // either they were declared at block scope or they are members of
11632 // one of the enclosing local classes.
11633 DC = Previous.getRepresentativeDecl()->getDeclContext();
11634 } else {
11635 // This is ill-formed, but provide the context that we would have
11636 // declared the function in, if we were permitted to, for error recovery.
11637 DC = FunctionContainingLocalClass;
11638 }
Richard Smith541b38b2013-09-20 01:15:31 +000011639 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011640
11641 // C++ [class.friend]p6:
11642 // A function can be defined in a friend declaration of a class if and
11643 // only if the class is a non-local class (9.8), the function name is
11644 // unqualified, and the function has namespace scope.
11645 if (D.isFunctionDefinition()) {
11646 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11647 }
11648
11649 // - There's no scope specifier, in which case we just go to the
11650 // appropriate scope and look for a function or function template
11651 // there as appropriate.
11652 } else if (SS.isInvalid() || !SS.isSet()) {
11653 // C++11 [namespace.memdef]p3:
11654 // If the name in a friend declaration is neither qualified nor
11655 // a template-id and the declaration is a function or an
11656 // elaborated-type-specifier, the lookup to determine whether
11657 // the entity has been previously declared shall not consider
11658 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011659 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011660
John McCallf7cfb222010-10-13 05:45:15 +000011661 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011662 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011663
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011664 // Skip class contexts. If someone can cite chapter and verse
11665 // for this behavior, that would be nice --- it's what GCC and
11666 // EDG do, and it seems like a reasonable intent, but the spec
11667 // really only says that checks for unqualified existing
11668 // declarations should stop at the nearest enclosing namespace,
11669 // not that they should only consider the nearest enclosing
11670 // namespace.
11671 while (DC->isRecord())
11672 DC = DC->getParent();
11673
11674 DeclContext *LookupDC = DC;
11675 while (LookupDC->isTransparentContext())
11676 LookupDC = LookupDC->getParent();
11677
11678 while (true) {
11679 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011680
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011681 if (!Previous.empty()) {
11682 DC = LookupDC;
11683 break;
John McCallf4776592010-10-14 22:22:28 +000011684 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011685
11686 if (isTemplateId) {
11687 if (isa<TranslationUnitDecl>(LookupDC)) break;
11688 } else {
11689 if (LookupDC->isFileContext()) break;
11690 }
11691 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011692 }
11693
John McCallccbc0322010-10-13 06:22:15 +000011694 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011695
John McCallde3fd222010-10-12 23:13:28 +000011696 // - There's a non-dependent scope specifier, in which case we
11697 // compute it and do a previous lookup there for a function
11698 // or function template.
11699 } else if (!SS.getScopeRep()->isDependent()) {
11700 DC = computeDeclContext(SS);
11701 if (!DC) return 0;
11702
11703 if (RequireCompleteDeclContext(SS, DC)) return 0;
11704
11705 LookupQualifiedName(Previous, DC);
11706
11707 // Ignore things found implicitly in the wrong scope.
11708 // TODO: better diagnostics for this case. Suggesting the right
11709 // qualified scope would be nice...
11710 LookupResult::Filter F = Previous.makeFilter();
11711 while (F.hasNext()) {
11712 NamedDecl *D = F.next();
11713 if (!DC->InEnclosingNamespaceSetOf(
11714 D->getDeclContext()->getRedeclContext()))
11715 F.erase();
11716 }
11717 F.done();
11718
11719 if (Previous.empty()) {
11720 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011721 Diag(Loc, diag::err_qualified_friend_not_found)
11722 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011723 return 0;
11724 }
11725
11726 // C++ [class.friend]p1: A friend of a class is a function or
11727 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011728 if (DC->Equals(CurContext))
11729 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011730 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011731 diag::warn_cxx98_compat_friend_is_member :
11732 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011733
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011734 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011735 // C++ [class.friend]p6:
11736 // A function can be defined in a friend declaration of a class if and
11737 // only if the class is a non-local class (9.8), the function name is
11738 // unqualified, and the function has namespace scope.
11739 SemaDiagnosticBuilder DB
11740 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11741
11742 DB << SS.getScopeRep();
11743 if (DC->isFileContext())
11744 DB << FixItHint::CreateRemoval(SS.getRange());
11745 SS.clear();
11746 }
John McCallde3fd222010-10-12 23:13:28 +000011747
11748 // - There's a scope specifier that does not match any template
11749 // parameter lists, in which case we use some arbitrary context,
11750 // create a method or method template, and wait for instantiation.
11751 // - There's a scope specifier that does match some template
11752 // parameter lists, which we don't handle right now.
11753 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011754 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011755 // C++ [class.friend]p6:
11756 // A function can be defined in a friend declaration of a class if and
11757 // only if the class is a non-local class (9.8), the function name is
11758 // unqualified, and the function has namespace scope.
11759 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11760 << SS.getScopeRep();
11761 }
11762
John McCallde3fd222010-10-12 23:13:28 +000011763 DC = CurContext;
11764 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011765 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011766
John McCallf7cfb222010-10-13 05:45:15 +000011767 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011768 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011769 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11770 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11771 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011772 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011773 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11774 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011775 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011776 }
John McCall07e91c02009-08-06 02:15:43 +000011777 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011778
Douglas Gregordd847ba2011-11-03 16:37:14 +000011779 // FIXME: This is an egregious hack to cope with cases where the scope stack
11780 // does not contain the declaration context, i.e., in an out-of-line
11781 // definition of a class.
11782 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11783 if (!DCScope) {
11784 FakeDCScope.setEntity(DC);
11785 DCScope = &FakeDCScope;
11786 }
Richard Smith114394f2013-08-09 04:35:01 +000011787
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011788 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011789 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011790 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011791 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011792
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011793 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011794
Richard Smith114394f2013-08-09 04:35:01 +000011795 // If we performed typo correction, we might have added a scope specifier
11796 // and changed the decl context.
11797 DC = ND->getDeclContext();
11798
John McCall759e32b2009-08-31 22:39:49 +000011799 // Add the function declaration to the appropriate lookup tables,
11800 // adjusting the redeclarations list as necessary. We don't
11801 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011802 //
John McCall759e32b2009-08-31 22:39:49 +000011803 // Also update the scope-based lookup if the target context's
11804 // lookup context is in lexical scope.
11805 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011806 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011807 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011808 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011809 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011810 }
John McCallaa74a0c2009-08-28 07:59:38 +000011811
11812 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011813 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011814 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011815 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011816 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011817
John McCalla0a96892012-08-10 03:15:35 +000011818 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011819 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011820 } else {
11821 if (DC->isRecord()) CheckFriendAccess(ND);
11822
John McCall2c2eb122010-10-16 06:59:13 +000011823 FunctionDecl *FD;
11824 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11825 FD = FTD->getTemplatedDecl();
11826 else
11827 FD = cast<FunctionDecl>(ND);
11828
David Majnemer502b0ed2013-06-25 23:09:30 +000011829 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11830 // default argument expression, that declaration shall be a definition
11831 // and shall be the only declaration of the function or function
11832 // template in the translation unit.
11833 if (functionDeclHasDefaultArgument(FD)) {
11834 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11835 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11836 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11837 } else if (!D.isFunctionDefinition())
11838 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11839 }
11840
John McCall2c2eb122010-10-16 06:59:13 +000011841 // Mark templated-scope function declarations as unsupported.
11842 if (FD->getNumTemplateParameterLists())
11843 FrD->setUnsupportedFriend(true);
11844 }
John McCallde3fd222010-10-12 23:13:28 +000011845
John McCall48871652010-08-21 09:40:31 +000011846 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011847}
11848
John McCall48871652010-08-21 09:40:31 +000011849void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11850 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011851
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011852 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011853 if (!Fn) {
11854 Diag(DelLoc, diag::err_deleted_non_function);
11855 return;
11856 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011857
Douglas Gregorec9fd132012-01-14 16:38:05 +000011858 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011859 // Don't consider the implicit declaration we generate for explicit
11860 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikieaf031a92012-06-29 18:00:25 +000011861 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11862 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011863 Diag(DelLoc, diag::err_deleted_decl_not_first);
11864 Diag(Prev->getLocation(), diag::note_previous_declaration);
11865 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011866 // If the declaration wasn't the first, we delete the function anyway for
11867 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011868 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011869 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011870
11871 if (Fn->isDeleted())
11872 return;
11873
11874 // See if we're deleting a function which is already known to override a
11875 // non-deleted virtual function.
11876 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11877 bool IssuedDiagnostic = false;
11878 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11879 E = MD->end_overridden_methods();
11880 I != E; ++I) {
11881 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11882 if (!IssuedDiagnostic) {
11883 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11884 IssuedDiagnostic = true;
11885 }
11886 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11887 }
11888 }
11889 }
11890
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011891 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011892}
Sebastian Redl4c018662009-04-27 21:33:24 +000011893
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011894void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011895 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011896
11897 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011898 if (MD->getParent()->isDependentType()) {
11899 MD->setDefaulted();
11900 MD->setExplicitlyDefaulted();
11901 return;
11902 }
11903
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011904 CXXSpecialMember Member = getSpecialMember(MD);
11905 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011906 if (!MD->isInvalidDecl())
11907 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011908 return;
11909 }
11910
11911 MD->setDefaulted();
11912 MD->setExplicitlyDefaulted();
11913
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011914 // If this definition appears within the record, do the checking when
11915 // the record is complete.
11916 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011917 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011918 // Find the uninstantiated declaration that actually had the '= default'
11919 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011920 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011921
Richard Smith3901dfe2013-03-27 00:22:47 +000011922 // If the method was defaulted on its first declaration, we will have
11923 // already performed the checking in CheckCompletedCXXClass. Such a
11924 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011925 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011926 return;
11927
Richard Smithd3b5c9082012-07-27 04:22:15 +000011928 CheckExplicitlyDefaultedSpecialMember(MD);
11929
Richard Smithbd305122012-12-11 01:14:52 +000011930 // The exception specification is needed because we are defining the
11931 // function.
11932 ResolveExceptionSpec(DefaultLoc,
11933 MD->getType()->castAs<FunctionProtoType>());
11934
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011935 if (MD->isInvalidDecl())
11936 return;
11937
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011938 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011939 case CXXDefaultConstructor:
11940 DefineImplicitDefaultConstructor(DefaultLoc,
11941 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000011942 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011943 case CXXCopyConstructor:
11944 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011945 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011946 case CXXCopyAssignment:
11947 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000011948 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011949 case CXXDestructor:
11950 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000011951 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011952 case CXXMoveConstructor:
11953 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000011954 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000011955 case CXXMoveAssignment:
11956 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011957 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011958 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000011959 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011960 }
11961 } else {
11962 Diag(DefaultLoc, diag::err_default_special_members);
11963 }
11964}
11965
Sebastian Redl4c018662009-04-27 21:33:24 +000011966static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000011967 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000011968 Stmt *SubStmt = *CI;
11969 if (!SubStmt)
11970 continue;
11971 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011972 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000011973 diag::err_return_in_constructor_handler);
11974 if (!isa<Expr>(SubStmt))
11975 SearchForReturnInStmt(Self, SubStmt);
11976 }
11977}
11978
11979void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11980 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11981 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11982 SearchForReturnInStmt(*this, Handler);
11983 }
11984}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000011985
David Blaikie68f71a32013-01-18 23:03:15 +000011986bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000011987 const CXXMethodDecl *Old) {
11988 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11989 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11990
11991 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11992
11993 // If the calling conventions match, everything is fine
11994 if (NewCC == OldCC)
11995 return false;
11996
Reid Kleckner78af0702013-08-27 23:08:25 +000011997 Diag(New->getLocation(),
11998 diag::err_conflicting_overriding_cc_attributes)
11999 << New->getDeclName() << New->getType() << Old->getType();
12000 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12001 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012002}
12003
Mike Stump11289f42009-09-09 15:08:12 +000012004bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012005 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000012006 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12007 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012008
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012009 if (Context.hasSameType(NewTy, OldTy) ||
12010 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012011 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012012
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012013 // Check if the return types are covariant
12014 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012015
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012016 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012017 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12018 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012019 NewClassTy = NewPT->getPointeeType();
12020 OldClassTy = OldPT->getPointeeType();
12021 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012022 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12023 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12024 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12025 NewClassTy = NewRT->getPointeeType();
12026 OldClassTy = OldRT->getPointeeType();
12027 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012028 }
12029 }
Mike Stump11289f42009-09-09 15:08:12 +000012030
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012031 // The return types aren't either both pointers or references to a class type.
12032 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012033 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012034 diag::err_different_return_type_for_overriding_virtual_function)
12035 << New->getDeclName() << NewTy << OldTy;
12036 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012037
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012038 return true;
12039 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012040
Anders Carlssone60365b2009-12-31 18:34:24 +000012041 // C++ [class.virtual]p6:
12042 // If the return type of D::f differs from the return type of B::f, the
12043 // class type in the return type of D::f shall be complete at the point of
12044 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012045 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12046 if (!RT->isBeingDefined() &&
12047 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012048 diag::err_covariant_return_incomplete,
12049 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012050 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012051 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012052
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012053 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012054 // Check if the new class derives from the old class.
12055 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12056 Diag(New->getLocation(),
12057 diag::err_covariant_return_not_derived)
12058 << New->getDeclName() << NewTy << OldTy;
12059 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12060 return true;
12061 }
Mike Stump11289f42009-09-09 15:08:12 +000012062
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012063 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012064 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012065 diag::err_covariant_return_inaccessible_base,
12066 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12067 // FIXME: Should this point to the return type?
12068 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012069 // FIXME: this note won't trigger for delayed access control
12070 // diagnostics, and it's impossible to get an undelayed error
12071 // here from access control during the original parse because
12072 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012073 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12074 return true;
12075 }
12076 }
Mike Stump11289f42009-09-09 15:08:12 +000012077
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012078 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012079 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012080 Diag(New->getLocation(),
12081 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012082 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012083 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12084 return true;
12085 };
Mike Stump11289f42009-09-09 15:08:12 +000012086
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012087
12088 // The new class type must have the same or less qualifiers as the old type.
12089 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12090 Diag(New->getLocation(),
12091 diag::err_covariant_return_type_class_type_more_qualified)
12092 << New->getDeclName() << NewTy << OldTy;
12093 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12094 return true;
12095 };
Mike Stump11289f42009-09-09 15:08:12 +000012096
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012097 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012098}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012099
Douglas Gregor21920e372009-12-01 17:24:26 +000012100/// \brief Mark the given method pure.
12101///
12102/// \param Method the method to be marked pure.
12103///
12104/// \param InitRange the source range that covers the "0" initializer.
12105bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012106 SourceLocation EndLoc = InitRange.getEnd();
12107 if (EndLoc.isValid())
12108 Method->setRangeEnd(EndLoc);
12109
Douglas Gregor21920e372009-12-01 17:24:26 +000012110 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12111 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012112 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012113 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012114
12115 if (!Method->isInvalidDecl())
12116 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12117 << Method->getDeclName() << InitRange;
12118 return true;
12119}
12120
Douglas Gregor926410d2012-02-21 02:22:07 +000012121/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012122static bool isStaticDataMember(const Decl *D) {
12123 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12124 return Var->isStaticDataMember();
12125
12126 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012127}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012128
John McCall1f4ee7b2009-12-19 09:28:58 +000012129/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12130/// an initializer for the out-of-line declaration 'Dcl'. The scope
12131/// is a fresh scope pushed for just this purpose.
12132///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012133/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12134/// static data member of class X, names should be looked up in the scope of
12135/// class X.
John McCall48871652010-08-21 09:40:31 +000012136void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012137 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012138 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012139
Richard Smitha2302242013-12-05 07:51:02 +000012140 // We will always have a nested name specifier here, but this declaration
12141 // might not be out of line if the specifier names the current namespace:
12142 // extern int n;
12143 // int ::n = 0;
12144 if (D->isOutOfLine())
12145 EnterDeclaratorContext(S, D->getDeclContext());
12146
Douglas Gregor926410d2012-02-21 02:22:07 +000012147 // If we are parsing the initializer for a static data member, push a
12148 // new expression evaluation context that is associated with this static
12149 // data member.
12150 if (isStaticDataMember(D))
12151 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012152}
12153
12154/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012155/// initializer for the out-of-line declaration 'D'.
12156void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012157 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012158 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012159
Douglas Gregor926410d2012-02-21 02:22:07 +000012160 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012161 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012162
Richard Smitha2302242013-12-05 07:51:02 +000012163 if (D->isOutOfLine())
12164 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012165}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012166
12167/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12168/// C++ if/switch/while/for statement.
12169/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012170DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012171 // C++ 6.4p2:
12172 // The declarator shall not specify a function or an array.
12173 // The type-specifier-seq shall not contain typedef and shall not declare a
12174 // new class or enumeration.
12175 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12176 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012177
12178 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012179 if (!Dcl)
12180 return true;
12181
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012182 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12183 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012184 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012185 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012186 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012187
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012188 return Dcl;
12189}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012190
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012191void Sema::LoadExternalVTableUses() {
12192 if (!ExternalSource)
12193 return;
12194
12195 SmallVector<ExternalVTableUse, 4> VTables;
12196 ExternalSource->ReadUsedVTables(VTables);
12197 SmallVector<VTableUse, 4> NewUses;
12198 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12199 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12200 = VTablesUsed.find(VTables[I].Record);
12201 // Even if a definition wasn't required before, it may be required now.
12202 if (Pos != VTablesUsed.end()) {
12203 if (!Pos->second && VTables[I].DefinitionRequired)
12204 Pos->second = true;
12205 continue;
12206 }
12207
12208 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12209 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12210 }
12211
12212 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12213}
12214
Douglas Gregor88d292c2010-05-13 16:44:06 +000012215void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12216 bool DefinitionRequired) {
12217 // Ignore any vtable uses in unevaluated operands or for classes that do
12218 // not have a vtable.
12219 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012220 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012221 return;
12222
Douglas Gregor88d292c2010-05-13 16:44:06 +000012223 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012224 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012225 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12226 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12227 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12228 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012229 // If we already had an entry, check to see if we are promoting this vtable
12230 // to required a definition. If so, we need to reappend to the VTableUses
12231 // list, since we may have already processed the first entry.
12232 if (DefinitionRequired && !Pos.first->second) {
12233 Pos.first->second = true;
12234 } else {
12235 // Otherwise, we can early exit.
12236 return;
12237 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012238 }
12239
12240 // Local classes need to have their virtual members marked
12241 // immediately. For all other classes, we mark their virtual members
12242 // at the end of the translation unit.
12243 if (Class->isLocalClass())
12244 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012245 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012246 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012247}
12248
Douglas Gregor88d292c2010-05-13 16:44:06 +000012249bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012250 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012251 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012252 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012253
Douglas Gregor88d292c2010-05-13 16:44:06 +000012254 // Note: The VTableUses vector could grow as a result of marking
12255 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012256 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012257 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012258 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012259 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012260 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012261 if (!Class)
12262 continue;
12263
12264 SourceLocation Loc = VTableUses[I].second;
12265
Richard Smithd3b5c9082012-07-27 04:22:15 +000012266 bool DefineVTable = true;
12267
Douglas Gregor88d292c2010-05-13 16:44:06 +000012268 // If this class has a key function, but that key function is
12269 // defined in another translation unit, we don't need to emit the
12270 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012271 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012272 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012273 // The key function is in another translation unit.
12274 DefineVTable = false;
12275 TemplateSpecializationKind TSK =
12276 KeyFunction->getTemplateSpecializationKind();
12277 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12278 TSK != TSK_ImplicitInstantiation &&
12279 "Instantiations don't have key functions");
12280 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012281 } else if (!KeyFunction) {
12282 // If we have a class with no key function that is the subject
12283 // of an explicit instantiation declaration, suppress the
12284 // vtable; it will live with the explicit instantiation
12285 // definition.
12286 bool IsExplicitInstantiationDeclaration
12287 = Class->getTemplateSpecializationKind()
12288 == TSK_ExplicitInstantiationDeclaration;
12289 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12290 REnd = Class->redecls_end();
12291 R != REnd; ++R) {
12292 TemplateSpecializationKind TSK
12293 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12294 if (TSK == TSK_ExplicitInstantiationDeclaration)
12295 IsExplicitInstantiationDeclaration = true;
12296 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12297 IsExplicitInstantiationDeclaration = false;
12298 break;
12299 }
12300 }
12301
12302 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012303 DefineVTable = false;
12304 }
12305
12306 // The exception specifications for all virtual members may be needed even
12307 // if we are not providing an authoritative form of the vtable in this TU.
12308 // We may choose to emit it available_externally anyway.
12309 if (!DefineVTable) {
12310 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12311 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012312 }
12313
12314 // Mark all of the virtual members of this class as referenced, so
12315 // that we can build a vtable. Then, tell the AST consumer that a
12316 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012317 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012318 MarkVirtualMembersReferenced(Loc, Class);
12319 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12320 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12321
12322 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012323 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012324 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012325 const FunctionDecl *KeyFunctionDef = 0;
12326 if (!KeyFunction ||
12327 (KeyFunction->hasBody(KeyFunctionDef) &&
12328 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012329 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12330 TSK_ExplicitInstantiationDefinition
12331 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12332 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012333 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012334 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012335 VTableUses.clear();
12336
Douglas Gregor97509692011-04-22 22:25:37 +000012337 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012338}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012339
Richard Smithd3b5c9082012-07-27 04:22:15 +000012340void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12341 const CXXRecordDecl *RD) {
12342 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12343 E = RD->method_end(); I != E; ++I)
12344 if ((*I)->isVirtual() && !(*I)->isPure())
12345 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12346}
12347
Rafael Espindola5b334082010-03-26 00:36:59 +000012348void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12349 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012350 // Mark all functions which will appear in RD's vtable as used.
12351 CXXFinalOverriderMap FinalOverriders;
12352 RD->getFinalOverriders(FinalOverriders);
12353 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12354 E = FinalOverriders.end();
12355 I != E; ++I) {
12356 for (OverridingMethods::const_iterator OI = I->second.begin(),
12357 OE = I->second.end();
12358 OI != OE; ++OI) {
12359 assert(OI->second.size() > 0 && "no final overrider");
12360 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012361
Richard Smith4ff9ff92012-07-07 06:59:51 +000012362 // C++ [basic.def.odr]p2:
12363 // [...] A virtual member function is used if it is not pure. [...]
12364 if (!Overrider->isPure())
12365 MarkFunctionReferenced(Loc, Overrider);
12366 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012367 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012368
12369 // Only classes that have virtual bases need a VTT.
12370 if (RD->getNumVBases() == 0)
12371 return;
12372
12373 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12374 e = RD->bases_end(); i != e; ++i) {
12375 const CXXRecordDecl *Base =
12376 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012377 if (Base->getNumVBases() == 0)
12378 continue;
12379 MarkVirtualMembersReferenced(Loc, Base);
12380 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012381}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012382
12383/// SetIvarInitializers - This routine builds initialization ASTs for the
12384/// Objective-C implementation whose ivars need be initialized.
12385void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012386 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012387 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012388 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012389 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012390 CollectIvarsToConstructOrDestruct(OID, ivars);
12391 if (ivars.empty())
12392 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012393 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012394 for (unsigned i = 0; i < ivars.size(); i++) {
12395 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012396 if (Field->isInvalidDecl())
12397 continue;
12398
Alexis Hunt1d792652011-01-08 20:30:50 +000012399 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012400 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12401 InitializationKind InitKind =
12402 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012403
12404 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12405 ExprResult MemberInit =
12406 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012407 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012408 // Note, MemberInit could actually come back empty if no initialization
12409 // is required (e.g., because it would call a trivial default constructor)
12410 if (!MemberInit.get() || MemberInit.isInvalid())
12411 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012412
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012413 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012414 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12415 SourceLocation(),
12416 MemberInit.takeAs<Expr>(),
12417 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012418 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012419
12420 // Be sure that the destructor is accessible and is marked as referenced.
12421 if (const RecordType *RecordTy
12422 = Context.getBaseElementType(Field->getType())
12423 ->getAs<RecordType>()) {
12424 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012425 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012426 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012427 CheckDestructorAccess(Field->getLocation(), Destructor,
12428 PDiag(diag::err_access_dtor_ivar)
12429 << Context.getBaseElementType(Field->getType()));
12430 }
12431 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012432 }
12433 ObjCImplementation->setIvarInitializers(Context,
12434 AllToInit.data(), AllToInit.size());
12435 }
12436}
Alexis Hunt6118d662011-05-04 05:57:24 +000012437
Alexis Hunt27a761d2011-05-04 23:29:54 +000012438static
12439void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12440 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12441 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12442 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12443 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012444 if (Ctor->isInvalidDecl())
12445 return;
12446
Richard Smith802c4b72012-08-23 06:16:52 +000012447 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12448
12449 // Target may not be determinable yet, for instance if this is a dependent
12450 // call in an uninstantiated template.
12451 if (Target) {
12452 const FunctionDecl *FNTarget = 0;
12453 (void)Target->hasBody(FNTarget);
12454 Target = const_cast<CXXConstructorDecl*>(
12455 cast_or_null<CXXConstructorDecl>(FNTarget));
12456 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012457
12458 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12459 // Avoid dereferencing a null pointer here.
12460 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12461
12462 if (!Current.insert(Canonical))
12463 return;
12464
12465 // We know that beyond here, we aren't chaining into a cycle.
12466 if (!Target || !Target->isDelegatingConstructor() ||
12467 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012468 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012469 Current.clear();
12470 // We've hit a cycle.
12471 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12472 Current.count(TCanonical)) {
12473 // If we haven't diagnosed this cycle yet, do so now.
12474 if (!Invalid.count(TCanonical)) {
12475 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012476 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012477 << Ctor;
12478
Richard Smith802c4b72012-08-23 06:16:52 +000012479 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012480 if (TCanonical != Canonical)
12481 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12482
12483 CXXConstructorDecl *C = Target;
12484 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012485 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012486 (void)C->getTargetConstructor()->hasBody(FNTarget);
12487 assert(FNTarget && "Ctor cycle through bodiless function");
12488
Richard Smith802c4b72012-08-23 06:16:52 +000012489 C = const_cast<CXXConstructorDecl*>(
12490 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012491 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12492 }
12493 }
12494
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012495 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012496 Current.clear();
12497 } else {
12498 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12499 }
12500}
12501
12502
Alexis Hunt6118d662011-05-04 05:57:24 +000012503void Sema::CheckDelegatingCtorCycles() {
12504 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12505
Douglas Gregorbae31202011-07-27 21:57:17 +000012506 for (DelegatingCtorDeclsType::iterator
12507 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012508 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012509 I != E; ++I)
12510 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012511
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012512 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12513 CE = Invalid.end();
12514 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012515 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012516}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012517
Douglas Gregor3024f072012-04-16 07:05:22 +000012518namespace {
12519 /// \brief AST visitor that finds references to the 'this' expression.
12520 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12521 Sema &S;
12522
12523 public:
12524 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12525
12526 bool VisitCXXThisExpr(CXXThisExpr *E) {
12527 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12528 << E->isImplicit();
12529 return false;
12530 }
12531 };
12532}
12533
12534bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12535 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12536 if (!TSInfo)
12537 return false;
12538
12539 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012540 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012541 if (!ProtoTL)
12542 return false;
12543
12544 // C++11 [expr.prim.general]p3:
12545 // [The expression this] shall not appear before the optional
12546 // cv-qualifier-seq and it shall not appear within the declaration of a
12547 // static member function (although its type and value category are defined
12548 // within a static member function as they are within a non-static member
12549 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012550 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012551 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012552 FindCXXThisExpr Finder(*this);
12553
12554 // If the return type came after the cv-qualifier-seq, check it now.
12555 if (Proto->hasTrailingReturn() &&
David Blaikie6adc78e2013-02-18 22:06:02 +000012556 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012557 return true;
12558
12559 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012560 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12561 return true;
12562
12563 return checkThisInStaticMemberFunctionAttributes(Method);
12564}
12565
12566bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12567 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12568 if (!TSInfo)
12569 return false;
12570
12571 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012572 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012573 if (!ProtoTL)
12574 return false;
12575
David Blaikie6adc78e2013-02-18 22:06:02 +000012576 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012577 FindCXXThisExpr Finder(*this);
12578
Douglas Gregor3024f072012-04-16 07:05:22 +000012579 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012580 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012581 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012582 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012583 case EST_DynamicNone:
12584 case EST_MSAny:
12585 case EST_None:
12586 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012587
Douglas Gregor3024f072012-04-16 07:05:22 +000012588 case EST_ComputedNoexcept:
12589 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12590 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012591
Douglas Gregor3024f072012-04-16 07:05:22 +000012592 case EST_Dynamic:
12593 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012594 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012595 E != EEnd; ++E) {
12596 if (!Finder.TraverseType(*E))
12597 return true;
12598 }
12599 break;
12600 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012601
12602 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012603}
12604
12605bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12606 FindCXXThisExpr Finder(*this);
12607
12608 // Check attributes.
12609 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12610 A != AEnd; ++A) {
12611 // FIXME: This should be emitted by tblgen.
12612 Expr *Arg = 0;
12613 ArrayRef<Expr *> Args;
12614 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12615 Arg = G->getArg();
12616 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12617 Arg = G->getArg();
12618 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12619 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12620 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12621 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12622 else if (ExclusiveLockFunctionAttr *ELF
12623 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12624 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12625 else if (SharedLockFunctionAttr *SLF
12626 = dyn_cast<SharedLockFunctionAttr>(*A))
12627 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12628 else if (ExclusiveTrylockFunctionAttr *ETLF
12629 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12630 Arg = ETLF->getSuccessValue();
12631 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12632 } else if (SharedTrylockFunctionAttr *STLF
12633 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12634 Arg = STLF->getSuccessValue();
12635 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12636 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12637 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12638 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12639 Arg = LR->getArg();
12640 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12641 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12642 else if (ExclusiveLocksRequiredAttr *ELR
12643 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12644 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12645 else if (SharedLocksRequiredAttr *SLR
12646 = dyn_cast<SharedLocksRequiredAttr>(*A))
12647 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12648
12649 if (Arg && !Finder.TraverseStmt(Arg))
12650 return true;
12651
12652 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12653 if (!Finder.TraverseStmt(Args[I]))
12654 return true;
12655 }
12656 }
12657
12658 return false;
12659}
12660
Douglas Gregor433e0532012-04-16 18:27:27 +000012661void
12662Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12663 ArrayRef<ParsedType> DynamicExceptions,
12664 ArrayRef<SourceRange> DynamicExceptionRanges,
12665 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012666 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012667 FunctionProtoType::ExtProtoInfo &EPI) {
12668 Exceptions.clear();
12669 EPI.ExceptionSpecType = EST;
12670 if (EST == EST_Dynamic) {
12671 Exceptions.reserve(DynamicExceptions.size());
12672 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12673 // FIXME: Preserve type source info.
12674 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12675
12676 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12677 collectUnexpandedParameterPacks(ET, Unexpanded);
12678 if (!Unexpanded.empty()) {
12679 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12680 UPPC_ExceptionType,
12681 Unexpanded);
12682 continue;
12683 }
12684
12685 // Check that the type is valid for an exception spec, and
12686 // drop it if not.
12687 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12688 Exceptions.push_back(ET);
12689 }
12690 EPI.NumExceptions = Exceptions.size();
12691 EPI.Exceptions = Exceptions.data();
12692 return;
12693 }
12694
12695 if (EST == EST_ComputedNoexcept) {
12696 // If an error occurred, there's no expression here.
12697 if (NoexceptExpr) {
12698 assert((NoexceptExpr->isTypeDependent() ||
12699 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12700 Context.BoolTy) &&
12701 "Parser should have made sure that the expression is boolean");
12702 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12703 EPI.ExceptionSpecType = EST_BasicNoexcept;
12704 return;
12705 }
12706
12707 if (!NoexceptExpr->isValueDependent())
12708 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012709 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012710 /*AllowFold*/ false).take();
12711 EPI.NoexceptExpr = NoexceptExpr;
12712 }
12713 return;
12714 }
12715}
12716
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012717/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12718Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12719 // Implicitly declared functions (e.g. copy constructors) are
12720 // __host__ __device__
12721 if (D->isImplicit())
12722 return CFT_HostDevice;
12723
12724 if (D->hasAttr<CUDAGlobalAttr>())
12725 return CFT_Global;
12726
12727 if (D->hasAttr<CUDADeviceAttr>()) {
12728 if (D->hasAttr<CUDAHostAttr>())
12729 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012730 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012731 }
12732
12733 return CFT_Host;
12734}
12735
12736bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12737 CUDAFunctionTarget CalleeTarget) {
12738 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12739 // Callable from the device only."
12740 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12741 return true;
12742
12743 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12744 // Callable from the host only."
12745 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12746 // Callable from the host only."
12747 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12748 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12749 return true;
12750
12751 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12752 return true;
12753
12754 return false;
12755}
John McCall5e77d762013-04-16 07:28:30 +000012756
12757/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12758///
12759MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12760 SourceLocation DeclStart,
12761 Declarator &D, Expr *BitWidth,
12762 InClassInitStyle InitStyle,
12763 AccessSpecifier AS,
12764 AttributeList *MSPropertyAttr) {
12765 IdentifierInfo *II = D.getIdentifier();
12766 if (!II) {
12767 Diag(DeclStart, diag::err_anonymous_property);
12768 return NULL;
12769 }
12770 SourceLocation Loc = D.getIdentifierLoc();
12771
12772 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12773 QualType T = TInfo->getType();
12774 if (getLangOpts().CPlusPlus) {
12775 CheckExtraCXXDefaultArguments(D);
12776
12777 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12778 UPPC_DataMemberType)) {
12779 D.setInvalidType();
12780 T = Context.IntTy;
12781 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12782 }
12783 }
12784
12785 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12786
12787 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12788 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12789 diag::err_invalid_thread)
12790 << DeclSpec::getSpecifierName(TSCS);
12791
12792 // Check to see if this name was declared as a member previously
12793 NamedDecl *PrevDecl = 0;
12794 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12795 LookupName(Previous, S);
12796 switch (Previous.getResultKind()) {
12797 case LookupResult::Found:
12798 case LookupResult::FoundUnresolvedValue:
12799 PrevDecl = Previous.getAsSingle<NamedDecl>();
12800 break;
12801
12802 case LookupResult::FoundOverloaded:
12803 PrevDecl = Previous.getRepresentativeDecl();
12804 break;
12805
12806 case LookupResult::NotFound:
12807 case LookupResult::NotFoundInCurrentInstantiation:
12808 case LookupResult::Ambiguous:
12809 break;
12810 }
12811
12812 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12813 // Maybe we will complain about the shadowed template parameter.
12814 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12815 // Just pretend that we didn't see the previous declaration.
12816 PrevDecl = 0;
12817 }
12818
12819 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12820 PrevDecl = 0;
12821
12822 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012823 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012824 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12825 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012826 ProcessDeclAttributes(TUScope, NewPD, D);
12827 NewPD->setAccess(AS);
12828
12829 if (NewPD->isInvalidDecl())
12830 Record->setInvalidDecl();
12831
12832 if (D.getDeclSpec().isModulePrivateSpecified())
12833 NewPD->setModulePrivate();
12834
12835 if (NewPD->isInvalidDecl() && PrevDecl) {
12836 // Don't introduce NewFD into scope; there's already something
12837 // with the same name in the same scope.
12838 } else if (II) {
12839 PushOnScopeChains(NewPD, S);
12840 } else
12841 Record->addDecl(NewPD);
12842
12843 return NewPD;
12844}