blob: 6ec344d1e3c08ea3d313d9c245a01db47942bdd3 [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;
883 if (!VD->hasInit()) {
884 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
Douglas Gregordc974572012-11-10 07:24:09 +00001230/// \brief Determine whether the given class is a base class of the given
1231/// class, including looking at dependent bases.
1232static bool findCircularInheritance(const CXXRecordDecl *Class,
1233 const CXXRecordDecl *Current) {
1234 SmallVector<const CXXRecordDecl*, 8> Queue;
1235
1236 Class = Class->getCanonicalDecl();
1237 while (true) {
1238 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1239 E = Current->bases_end();
1240 I != E; ++I) {
1241 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1242 if (!Base)
1243 continue;
1244
1245 Base = Base->getDefinition();
1246 if (!Base)
1247 continue;
1248
1249 if (Base->getCanonicalDecl() == Class)
1250 return true;
1251
1252 Queue.push_back(Base);
1253 }
1254
1255 if (Queue.empty())
1256 return false;
1257
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001258 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001259 }
1260
1261 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001262}
1263
Mike Stump11289f42009-09-09 15:08:12 +00001264/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001265///
1266/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1267/// and returns NULL otherwise.
1268CXXBaseSpecifier *
1269Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1270 SourceRange SpecifierRange,
1271 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001272 TypeSourceInfo *TInfo,
1273 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001274 QualType BaseType = TInfo->getType();
1275
Douglas Gregor463421d2009-03-03 04:44:36 +00001276 // C++ [class.union]p1:
1277 // A union shall not have base classes.
1278 if (Class->isUnion()) {
1279 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1280 << SpecifierRange;
1281 return 0;
1282 }
1283
Douglas Gregor752a5952011-01-03 22:36:02 +00001284 if (EllipsisLoc.isValid() &&
1285 !TInfo->getType()->containsUnexpandedParameterPack()) {
1286 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1287 << TInfo->getTypeLoc().getSourceRange();
1288 EllipsisLoc = SourceLocation();
1289 }
Douglas Gregor62004702012-11-10 01:18:17 +00001290
1291 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1292
1293 if (BaseType->isDependentType()) {
1294 // Make sure that we don't have circular inheritance among our dependent
1295 // bases. For non-dependent bases, the check for completeness below handles
1296 // this.
1297 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1298 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1299 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001300 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001301 Diag(BaseLoc, diag::err_circular_inheritance)
1302 << BaseType << Context.getTypeDeclType(Class);
1303
1304 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1305 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1306 << BaseType;
1307
1308 return 0;
1309 }
1310 }
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001313 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001314 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001315 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001316
1317 // Base specifiers must be record types.
1318 if (!BaseType->isRecordType()) {
1319 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1320 return 0;
1321 }
1322
1323 // C++ [class.union]p1:
1324 // A union shall not be used as a base class.
1325 if (BaseType->isUnionType()) {
1326 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1327 return 0;
1328 }
1329
1330 // C++ [class.derived]p2:
1331 // The class-name in a base-specifier shall not be an incompletely
1332 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001333 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001334 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001335 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001336 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001337 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001338
Eli Friedmanc96d4962009-08-15 21:55:26 +00001339 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001340 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001341 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001342 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001343 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001344 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001345 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001346
Anders Carlsson65c76d32011-03-25 14:55:14 +00001347 // C++ [class]p3:
1348 // If a class is marked final and it appears as a base-type-specifier in
1349 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001350 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001351 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1352 << CXXBaseDecl->getDeclName();
1353 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1354 << CXXBaseDecl->getDeclName();
1355 return 0;
1356 }
1357
John McCall3696dcb2010-08-17 07:23:57 +00001358 if (BaseDecl->isInvalidDecl())
1359 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001360
1361 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001362 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001363 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001364 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001365}
1366
Douglas Gregor556877c2008-04-13 21:30:24 +00001367/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1368/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001369/// example:
1370/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001371/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001372BaseResult
John McCall48871652010-08-21 09:40:31 +00001373Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001374 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001375 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001376 ParsedType basetype, SourceLocation BaseLoc,
1377 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001378 if (!classdecl)
1379 return true;
1380
Douglas Gregorc40290e2009-03-09 23:48:35 +00001381 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001382 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001383 if (!Class)
1384 return true;
1385
Richard Smith4c96e992013-02-19 23:47:15 +00001386 // We do not support any C++11 attributes on base-specifiers yet.
1387 // Diagnose any attributes we see.
1388 if (!Attributes.empty()) {
1389 for (AttributeList *Attr = Attributes.getList(); Attr;
1390 Attr = Attr->getNext()) {
1391 if (Attr->isInvalid() ||
1392 Attr->getKind() == AttributeList::IgnoredAttribute)
1393 continue;
1394 Diag(Attr->getLoc(),
1395 Attr->getKind() == AttributeList::UnknownAttribute
1396 ? diag::warn_unknown_attribute_ignored
1397 : diag::err_base_specifier_attribute)
1398 << Attr->getName();
1399 }
1400 }
1401
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 TypeSourceInfo *TInfo = 0;
1403 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001404
Douglas Gregor752a5952011-01-03 22:36:02 +00001405 if (EllipsisLoc.isInvalid() &&
1406 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001407 UPPC_BaseType))
1408 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001409
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001411 Virtual, Access, TInfo,
1412 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001413 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001414 else
1415 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001416
Douglas Gregor463421d2009-03-03 04:44:36 +00001417 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001418}
Douglas Gregor556877c2008-04-13 21:30:24 +00001419
Douglas Gregor463421d2009-03-03 04:44:36 +00001420/// \brief Performs the actual work of attaching the given base class
1421/// specifiers to a C++ class.
1422bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1423 unsigned NumBases) {
1424 if (NumBases == 0)
1425 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001426
1427 // Used to keep track of which base types we have already seen, so
1428 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001429 // that the key is always the unqualified canonical type of the base
1430 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001431 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1432
1433 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001434 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001435 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001436 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001437 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001438 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001439 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001440
1441 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1442 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001443 // C++ [class.mi]p3:
1444 // A class shall not be specified as a direct base class of a
1445 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001446 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001447 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001448 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001450
1451 // Delete the duplicate base class specifier; we're going to
1452 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001453 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001454
1455 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001456 } else {
1457 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001458 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001459 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001460 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1461 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1462 if (Class->isInterface() &&
1463 (!RD->isInterface() ||
1464 KnownBase->getAccessSpecifier() != AS_public)) {
1465 // The Microsoft extension __interface does not permit bases that
1466 // are not themselves public interfaces.
1467 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1468 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1469 << RD->getSourceRange();
1470 Invalid = true;
1471 }
1472 if (RD->hasAttr<WeakAttr>())
1473 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1474 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001475 }
1476 }
1477
1478 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001479 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001480
1481 // Delete the remaining (good) base class specifiers, since their
1482 // data has been copied into the CXXRecordDecl.
1483 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001484 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001485
1486 return Invalid;
1487}
1488
1489/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1490/// class, after checking whether there are any duplicate base
1491/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001492void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001493 unsigned NumBases) {
1494 if (!ClassDecl || !Bases || !NumBases)
1495 return;
1496
1497 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001498 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001499}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001500
Douglas Gregor36d1b142009-10-06 17:59:45 +00001501/// \brief Determine whether the type \p Derived is a C++ class that is
1502/// derived from the type \p Base.
1503bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001504 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001505 return false;
John McCalle78aac42010-03-10 03:28:59 +00001506
Douglas Gregor45bb4832013-03-26 23:36:30 +00001507 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001508 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001509 return false;
1510
Douglas Gregor45bb4832013-03-26 23:36:30 +00001511 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001512 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001513 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001514
1515 // If either the base or the derived type is invalid, don't try to
1516 // check whether one is derived from the other.
1517 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1518 return false;
1519
John McCall67da35c2010-02-04 22:26:26 +00001520 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1521 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001522}
1523
1524/// \brief Determine whether the type \p Derived is a C++ class that is
1525/// derived from the type \p Base.
1526bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001527 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001528 return false;
1529
Douglas Gregor45bb4832013-03-26 23:36:30 +00001530 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001531 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001532 return false;
1533
Douglas Gregor45bb4832013-03-26 23:36:30 +00001534 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001535 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001536 return false;
1537
Douglas Gregor36d1b142009-10-06 17:59:45 +00001538 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1539}
1540
Anders Carlssona70cff62010-04-24 19:06:50 +00001541void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001542 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001543 assert(BasePathArray.empty() && "Base path array must be empty!");
1544 assert(Paths.isRecordingPaths() && "Must record paths!");
1545
1546 const CXXBasePath &Path = Paths.front();
1547
1548 // We first go backward and check if we have a virtual base.
1549 // FIXME: It would be better if CXXBasePath had the base specifier for
1550 // the nearest virtual base.
1551 unsigned Start = 0;
1552 for (unsigned I = Path.size(); I != 0; --I) {
1553 if (Path[I - 1].Base->isVirtual()) {
1554 Start = I - 1;
1555 break;
1556 }
1557 }
1558
1559 // Now add all bases.
1560 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001561 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001562}
1563
Douglas Gregor88d292c2010-05-13 16:44:06 +00001564/// \brief Determine whether the given base path includes a virtual
1565/// base class.
John McCallcf142162010-08-07 06:22:56 +00001566bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1567 for (CXXCastPath::const_iterator B = BasePath.begin(),
1568 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001569 B != BEnd; ++B)
1570 if ((*B)->isVirtual())
1571 return true;
1572
1573 return false;
1574}
1575
Douglas Gregor36d1b142009-10-06 17:59:45 +00001576/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1577/// conversion (where Derived and Base are class types) is
1578/// well-formed, meaning that the conversion is unambiguous (and
1579/// that all of the base classes are accessible). Returns true
1580/// and emits a diagnostic if the code is ill-formed, returns false
1581/// otherwise. Loc is the location where this routine should point to
1582/// if there is an error, and Range is the source range to highlight
1583/// if there is an error.
1584bool
1585Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001586 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 unsigned AmbigiousBaseConvID,
1588 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001589 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001590 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001591 // First, determine whether the path from Derived to Base is
1592 // ambiguous. This is slightly more expensive than checking whether
1593 // the Derived to Base conversion exists, because here we need to
1594 // explore multiple paths to determine if there is an ambiguity.
1595 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1596 /*DetectVirtual=*/false);
1597 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1598 assert(DerivationOkay &&
1599 "Can only be used with a derived-to-base conversion");
1600 (void)DerivationOkay;
1601
1602 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001603 if (InaccessibleBaseID) {
1604 // Check that the base class can be accessed.
1605 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1606 InaccessibleBaseID)) {
1607 case AR_inaccessible:
1608 return true;
1609 case AR_accessible:
1610 case AR_dependent:
1611 case AR_delayed:
1612 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001613 }
John McCall5b0829a2010-02-10 09:31:12 +00001614 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001615
1616 // Build a base path if necessary.
1617 if (BasePath)
1618 BuildBasePathArray(Paths, *BasePath);
1619 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001620 }
1621
David Majnemer626032f2013-06-22 06:43:58 +00001622 if (AmbigiousBaseConvID) {
1623 // We know that the derived-to-base conversion is ambiguous, and
1624 // we're going to produce a diagnostic. Perform the derived-to-base
1625 // search just one more time to compute all of the possible paths so
1626 // that we can print them out. This is more expensive than any of
1627 // the previous derived-to-base checks we've done, but at this point
1628 // performance isn't as much of an issue.
1629 Paths.clear();
1630 Paths.setRecordingPaths(true);
1631 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1632 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1633 (void)StillOkay;
1634
1635 // Build up a textual representation of the ambiguous paths, e.g.,
1636 // D -> B -> A, that will be used to illustrate the ambiguous
1637 // conversions in the diagnostic. We only print one of the paths
1638 // to each base class subobject.
1639 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1640
1641 Diag(Loc, AmbigiousBaseConvID)
1642 << Derived << Base << PathDisplayStr << Range << Name;
1643 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 return true;
1645}
1646
1647bool
1648Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001649 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001650 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001651 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001653 IgnoreAccess ? 0
1654 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001655 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001656 Loc, Range, DeclarationName(),
1657 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658}
1659
1660
1661/// @brief Builds a string representing ambiguous paths from a
1662/// specific derived class to different subobjects of the same base
1663/// class.
1664///
1665/// This function builds a string that can be used in error messages
1666/// to show the different paths that one can take through the
1667/// inheritance hierarchy to go from the derived class to different
1668/// subobjects of a base class. The result looks something like this:
1669/// @code
1670/// struct D -> struct B -> struct A
1671/// struct D -> struct C -> struct A
1672/// @endcode
1673std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1674 std::string PathDisplayStr;
1675 std::set<unsigned> DisplayedPaths;
1676 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1677 Path != Paths.end(); ++Path) {
1678 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1679 // We haven't displayed a path to this particular base
1680 // class subobject yet.
1681 PathDisplayStr += "\n ";
1682 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1683 for (CXXBasePath::const_iterator Element = Path->begin();
1684 Element != Path->end(); ++Element)
1685 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1686 }
1687 }
1688
1689 return PathDisplayStr;
1690}
1691
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001692//===----------------------------------------------------------------------===//
1693// C++ class member Handling
1694//===----------------------------------------------------------------------===//
1695
Abramo Bagnarad7340582010-06-05 05:09:32 +00001696/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001697bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1698 SourceLocation ASLoc,
1699 SourceLocation ColonLoc,
1700 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001701 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001702 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001703 ASLoc, ColonLoc);
1704 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001705 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001706}
1707
Richard Smith18f07db2012-08-06 03:25:17 +00001708/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001709void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001710 if (D->isInvalidDecl())
1711 return;
1712
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001713 // We only care about "override" and "final" declarations.
1714 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1715 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001716
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001717 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001718
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001719 // We can't check dependent instance methods.
1720 if (MD && MD->isInstance() &&
1721 (MD->getParent()->hasAnyDependentBases() ||
1722 MD->getType()->isDependentType()))
1723 return;
1724
1725 if (MD && !MD->isVirtual()) {
1726 // If we have a non-virtual method, check if if hides a virtual method.
1727 // (In that case, it's most likely the method has the wrong type.)
1728 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1729 FindHiddenVirtualMethods(MD, OverloadedMethods);
1730
1731 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001732 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1733 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001734 diag::override_keyword_hides_virtual_member_function)
1735 << "override" << (OverloadedMethods.size() > 1);
1736 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001737 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001738 diag::override_keyword_hides_virtual_member_function)
1739 << "final" << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001740 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001741 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1742 MD->setInvalidDecl();
1743 return;
1744 }
1745 // Fall through into the general case diagnostic.
1746 // FIXME: We might want to attempt typo correction here.
1747 }
1748
1749 if (!MD || !MD->isVirtual()) {
1750 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1751 Diag(OA->getLocation(),
1752 diag::override_keyword_only_allowed_on_virtual_member_functions)
1753 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1754 D->dropAttr<OverrideAttr>();
1755 }
1756 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1757 Diag(FA->getLocation(),
1758 diag::override_keyword_only_allowed_on_virtual_member_functions)
1759 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1760 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001761 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001762 return;
1763 }
Richard Smith18f07db2012-08-06 03:25:17 +00001764
Richard Smith18f07db2012-08-06 03:25:17 +00001765 // C++11 [class.virtual]p5:
1766 // If a virtual function is marked with the virt-specifier override and
1767 // does not override a member function of a base class, the program is
1768 // ill-formed.
1769 bool HasOverriddenMethods =
1770 MD->begin_overridden_methods() != MD->end_overridden_methods();
1771 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1772 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1773 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001774}
1775
Richard Smith18f07db2012-08-06 03:25:17 +00001776/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001777/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001778/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001779bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1780 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001781 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001782 return false;
1783
1784 Diag(New->getLocation(), diag::err_final_function_overridden)
1785 << New->getDeclName();
1786 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1787 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001788}
1789
Daniel Jasper0baec5492012-06-06 08:32:04 +00001790static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001791 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1792 // FIXME: Destruction of ObjC lifetime types has side-effects.
1793 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1794 return !RD->isCompleteDefinition() ||
1795 !RD->hasTrivialDefaultConstructor() ||
1796 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001797 return false;
1798}
1799
John McCall5e77d762013-04-16 07:28:30 +00001800static AttributeList *getMSPropertyAttr(AttributeList *list) {
1801 for (AttributeList* it = list; it != 0; it = it->getNext())
1802 if (it->isDeclspecPropertyAttribute())
1803 return it;
1804 return 0;
1805}
1806
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001807/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1808/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001809/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001810/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1811/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001812NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001813Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001814 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001815 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001816 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001817 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001818 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1819 DeclarationName Name = NameInfo.getName();
1820 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001821
1822 // For anonymous bitfields, the location should point to the type.
1823 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001824 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001825
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001826 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001827
John McCallb1cd7da2010-06-04 08:34:12 +00001828 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001829 assert(!DS.isFriendSpecified());
1830
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001831 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001832
John McCalldb632ac2012-09-25 07:32:39 +00001833 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1834 // The Microsoft extension __interface only permits public member functions
1835 // and prohibits constructors, destructors, operators, non-public member
1836 // functions, static methods and data members.
1837 unsigned InvalidDecl;
1838 bool ShowDeclName = true;
1839 if (!isFunc)
1840 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1841 else if (AS != AS_public)
1842 InvalidDecl = 2;
1843 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1844 InvalidDecl = 3;
1845 else switch (Name.getNameKind()) {
1846 case DeclarationName::CXXConstructorName:
1847 InvalidDecl = 4;
1848 ShowDeclName = false;
1849 break;
1850
1851 case DeclarationName::CXXDestructorName:
1852 InvalidDecl = 5;
1853 ShowDeclName = false;
1854 break;
1855
1856 case DeclarationName::CXXOperatorName:
1857 case DeclarationName::CXXConversionFunctionName:
1858 InvalidDecl = 6;
1859 break;
1860
1861 default:
1862 InvalidDecl = 0;
1863 break;
1864 }
1865
1866 if (InvalidDecl) {
1867 if (ShowDeclName)
1868 Diag(Loc, diag::err_invalid_member_in_interface)
1869 << (InvalidDecl-1) << Name;
1870 else
1871 Diag(Loc, diag::err_invalid_member_in_interface)
1872 << (InvalidDecl-1) << "";
1873 return 0;
1874 }
1875 }
1876
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001877 // C++ 9.2p6: A member shall not be declared to have automatic storage
1878 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001879 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1880 // data members and cannot be applied to names declared const or static,
1881 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001882 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001883 case DeclSpec::SCS_unspecified:
1884 case DeclSpec::SCS_typedef:
1885 case DeclSpec::SCS_static:
1886 break;
1887 case DeclSpec::SCS_mutable:
1888 if (isFunc) {
1889 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001890
Richard Smithb4a9e862013-04-12 22:46:28 +00001891 // FIXME: It would be nicer if the keyword was ignored only for this
1892 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001893 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001894 }
1895 break;
1896 default:
1897 Diag(DS.getStorageClassSpecLoc(),
1898 diag::err_storageclass_invalid_for_member);
1899 D.getMutableDeclSpec().ClearStorageClassSpecs();
1900 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001901 }
1902
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001905 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001906
David Blaikie35506f82013-01-30 01:22:18 +00001907 if (DS.isConstexprSpecified() && isInstField) {
1908 SemaDiagnosticBuilder B =
1909 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1910 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1911 if (InitStyle == ICIS_NoInit) {
1912 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1913 D.getMutableDeclSpec().ClearConstexprSpec();
1914 const char *PrevSpec;
1915 unsigned DiagID;
1916 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1917 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001918 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001919 assert(!Failed && "Making a constexpr member const shouldn't fail");
1920 } else {
1921 B << 1;
1922 const char *PrevSpec;
1923 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001924 if (D.getMutableDeclSpec().SetStorageClassSpec(
1925 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001926 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001927 "This is the only DeclSpec that should fail to be applied");
1928 B << 1;
1929 } else {
1930 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1931 isInstField = false;
1932 }
1933 }
1934 }
1935
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001936 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001937 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001938 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001939
1940 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001941 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001942 Diag(Loc, diag::err_bad_variable_name)
1943 << Name;
1944 return 0;
1945 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001946
Benjamin Kramer365082d2012-05-19 16:34:46 +00001947 IdentifierInfo *II = Name.getAsIdentifierInfo();
1948
Douglas Gregor7c26c042011-09-21 14:40:46 +00001949 // Member field could not be with "template" keyword.
1950 // So TemplateParameterLists should be empty in this case.
1951 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001952 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00001953 if (TemplateParams->size()) {
1954 // There is no such thing as a member field template.
1955 Diag(D.getIdentifierLoc(), diag::err_template_member)
1956 << II
1957 << SourceRange(TemplateParams->getTemplateLoc(),
1958 TemplateParams->getRAngleLoc());
1959 } else {
1960 // There is an extraneous 'template<>' for this member.
1961 Diag(TemplateParams->getTemplateLoc(),
1962 diag::err_template_member_noparams)
1963 << II
1964 << SourceRange(TemplateParams->getTemplateLoc(),
1965 TemplateParams->getRAngleLoc());
1966 }
1967 return 0;
1968 }
1969
Douglas Gregora007d362010-10-13 22:19:53 +00001970 if (SS.isSet() && !SS.isInvalid()) {
1971 // The user provided a superfluous scope specifier inside a class
1972 // definition:
1973 //
1974 // class X {
1975 // int X::member;
1976 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00001977 if (DeclContext *DC = computeDeclContext(SS, false))
1978 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00001979 else
1980 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1981 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001982
Douglas Gregora007d362010-10-13 22:19:53 +00001983 SS.clear();
1984 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001985
John McCall5e77d762013-04-16 07:28:30 +00001986 AttributeList *MSPropertyAttr =
1987 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00001988 if (MSPropertyAttr) {
1989 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1990 BitWidth, InitStyle, AS, MSPropertyAttr);
1991 if (!Member)
1992 return 0;
1993 isInstField = false;
1994 } else {
1995 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1996 BitWidth, InitStyle, AS);
1997 assert(Member && "HandleField never returns null");
1998 }
1999 } else {
2000 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2001
2002 Member = HandleDeclarator(S, D, TemplateParameterLists);
2003 if (!Member)
2004 return 0;
2005
2006 // Non-instance-fields can't have a bitfield.
2007 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002008 if (Member->isInvalidDecl()) {
2009 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002010 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002011 // C++ 9.6p3: A bit-field shall not be a static member.
2012 // "static member 'A' cannot be a bit-field"
2013 Diag(Loc, diag::err_static_not_bitfield)
2014 << Name << BitWidth->getSourceRange();
2015 } else if (isa<TypedefDecl>(Member)) {
2016 // "typedef member 'x' cannot be a bit-field"
2017 Diag(Loc, diag::err_typedef_not_bitfield)
2018 << Name << BitWidth->getSourceRange();
2019 } else {
2020 // A function typedef ("typedef int f(); f a;").
2021 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2022 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002023 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002024 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Chris Lattnerd26760a2009-03-05 23:01:03 +00002027 BitWidth = 0;
2028 Member->setInvalidDecl();
2029 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002030
2031 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002032
Larisse Voufo39a1e502013-08-06 01:03:05 +00002033 // If we have declared a member function template or static data member
2034 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002035 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2036 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002037 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2038 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002039 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002040
Richard Smith18f07db2012-08-06 03:25:17 +00002041 if (VS.isOverrideSpecified())
2042 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2043 if (VS.isFinalSpecified())
2044 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonfd835532011-01-20 05:57:14 +00002045
Douglas Gregorf2f08062011-03-08 17:10:18 +00002046 if (VS.getLastLocation().isValid()) {
2047 // Update the end location of a method that has a virt-specifiers.
2048 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2049 MD->setRangeEnd(VS.getLastLocation());
2050 }
Richard Smith18f07db2012-08-06 03:25:17 +00002051
Anders Carlssonc87f8612011-01-20 06:29:02 +00002052 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002053
Douglas Gregor92751d42008-11-17 22:58:34 +00002054 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002055
Daniel Jasper0baec5492012-06-06 08:32:04 +00002056 if (isInstField) {
2057 FieldDecl *FD = cast<FieldDecl>(Member);
2058 FieldCollector->Add(FD);
2059
2060 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2061 FD->getLocation())
2062 != DiagnosticsEngine::Ignored) {
2063 // Remember all explicit private FieldDecls that have a name, no side
2064 // effects and are not part of a dependent type declaration.
2065 if (!FD->isImplicit() && FD->getDeclName() &&
2066 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002067 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002068 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002069 !InitializationHasSideEffects(*FD))
2070 UnusedPrivateFields.insert(FD);
2071 }
2072 }
2073
John McCall48871652010-08-21 09:40:31 +00002074 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002075}
2076
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002077namespace {
2078 class UninitializedFieldVisitor
2079 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2080 Sema &S;
Richard Trieu406e65c2013-09-20 03:03:06 +00002081 // If VD is null, this visitor will only update the Decls set.
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002082 ValueDecl *VD;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002083 bool isReferenceType;
Richard Trieu406e65c2013-09-20 03:03:06 +00002084 // List of Decls to generate a warning on.
2085 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2086 bool WarnOnSelfReference;
2087 // If non-null, add a note to the warning pointing back to the constructor.
2088 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002089 public:
2090 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu406e65c2013-09-20 03:03:06 +00002091 UninitializedFieldVisitor(Sema &S, ValueDecl *VD,
2092 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2093 bool WarnOnSelfReference,
2094 const CXXConstructorDecl *Constructor)
2095 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls),
2096 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) {
2097 // When VD is null, this visitor is used to detect initialization of other
2098 // fields.
2099 if (VD) {
2100 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2101 this->VD = IFD->getAnonField();
2102 else
2103 this->VD = VD;
2104 isReferenceType = this->VD->getType()->isReferenceType();
2105 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002106 }
2107
Richard Trieufd687772013-09-16 20:46:50 +00002108 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002109 if (!VD)
2110 return;
2111
Richard Trieufd687772013-09-16 20:46:50 +00002112 if (CheckReferenceOnly && !isReferenceType)
2113 return;
2114
Richard Trieu1bc22c12013-09-13 03:20:53 +00002115 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2116 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002117
Richard Trieu1bc22c12013-09-13 03:20:53 +00002118 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2119 // or union.
2120 MemberExpr *FieldME = ME;
2121
2122 Expr *Base = ME;
2123 while (isa<MemberExpr>(Base)) {
2124 ME = cast<MemberExpr>(Base);
2125
2126 if (isa<VarDecl>(ME->getMemberDecl()))
2127 return;
2128
2129 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2130 if (!FD->isAnonymousStructOrUnion())
2131 FieldME = ME;
2132
2133 Base = ME->getBase();
2134 }
2135
Richard Trieufd687772013-09-16 20:46:50 +00002136 if (!isa<CXXThisExpr>(Base))
2137 return;
2138
Richard Trieu406e65c2013-09-20 03:03:06 +00002139 ValueDecl* FoundVD = FieldME->getMemberDecl();
2140
2141 if (VD == FoundVD) {
2142 if (!WarnOnSelfReference)
2143 return;
2144
Richard Trieufd687772013-09-16 20:46:50 +00002145 unsigned diag = isReferenceType
Richard Trieu1bc22c12013-09-13 03:20:53 +00002146 ? diag::warn_reference_field_is_uninit
2147 : diag::warn_field_is_uninit;
2148 S.Diag(FieldME->getExprLoc(), diag) << VD;
Richard Trieu406e65c2013-09-20 03:03:06 +00002149 if (Constructor)
2150 S.Diag(Constructor->getLocation(),
2151 diag::note_uninit_in_this_constructor);
2152 return;
2153 }
2154
2155 if (CheckReferenceOnly)
2156 return;
2157
2158 if (Decls.count(FoundVD)) {
2159 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD;
2160 if (Constructor)
2161 S.Diag(Constructor->getLocation(),
2162 diag::note_uninit_in_this_constructor);
2163
Richard Trieu1bc22c12013-09-13 03:20:53 +00002164 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002165 }
2166
2167 void HandleValue(Expr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002168 if (!VD)
2169 return;
2170
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002171 E = E->IgnoreParens();
2172
2173 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002174 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002175 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002176 }
2177
2178 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2179 HandleValue(CO->getTrueExpr());
2180 HandleValue(CO->getFalseExpr());
2181 return;
2182 }
2183
2184 if (BinaryConditionalOperator *BCO =
2185 dyn_cast<BinaryConditionalOperator>(E)) {
2186 HandleValue(BCO->getCommon());
2187 HandleValue(BCO->getFalseExpr());
2188 return;
2189 }
2190
2191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2192 switch (BO->getOpcode()) {
2193 default:
2194 return;
2195 case(BO_PtrMemD):
2196 case(BO_PtrMemI):
2197 HandleValue(BO->getLHS());
2198 return;
2199 case(BO_Comma):
2200 HandleValue(BO->getRHS());
2201 return;
2202 }
2203 }
2204 }
2205
Richard Trieu1bc22c12013-09-13 03:20:53 +00002206 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieufd687772013-09-16 20:46:50 +00002207 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002208
2209 Inherited::VisitMemberExpr(ME);
2210 }
2211
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002212 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2213 if (E->getCastKind() == CK_LValueToRValue)
2214 HandleValue(E->getSubExpr());
2215
2216 Inherited::VisitImplicitCastExpr(E);
2217 }
2218
Richard Trieu1bc22c12013-09-13 03:20:53 +00002219 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002220 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002221 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2222 if (ICE->getCastKind() == CK_NoOp)
2223 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002224 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002225
2226 Inherited::VisitCXXConstructExpr(E);
2227 }
2228
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002229 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2230 Expr *Callee = E->getCallee();
2231 if (isa<MemberExpr>(Callee))
2232 HandleValue(Callee);
2233
2234 Inherited::VisitCXXMemberCallExpr(E);
2235 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002236
2237 void VisitBinaryOperator(BinaryOperator *E) {
2238 // If a field assignment is detected, remove the field from the
2239 // uninitiailized field set.
2240 if (E->getOpcode() == BO_Assign)
2241 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2242 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2243 Decls.erase(FD);
2244
2245 Inherited::VisitBinaryOperator(E);
2246 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002247 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002248 static void CheckInitExprContainsUninitializedFields(
2249 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2250 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) {
2251 if (Decls.size() == 0 && !WarnOnSelfReference)
2252 return;
2253
Richard Trieu1bc22c12013-09-13 03:20:53 +00002254 if (E)
Richard Trieu406e65c2013-09-20 03:03:06 +00002255 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor)
2256 .Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002257 }
2258} // namespace
2259
Richard Smith938f40b2011-06-11 17:19:42 +00002260/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00002261/// in-class initializer for a non-static C++ class member, and after
2262/// instantiating an in-class initializer in a class template. Such actions
2263/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00002264void
Richard Smith2b013182012-06-10 03:12:00 +00002265Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith938f40b2011-06-11 17:19:42 +00002266 Expr *InitExpr) {
2267 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002268 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2269 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002270
2271 if (!InitExpr) {
2272 FD->setInvalidDecl();
2273 FD->removeInClassInitializer();
2274 return;
2275 }
2276
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002277 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2278 FD->setInvalidDecl();
2279 FD->removeInClassInitializer();
2280 return;
2281 }
2282
Richard Smith938f40b2011-06-11 17:19:42 +00002283 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002284 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002285 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002286 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002287 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002288 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002289 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2290 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002291 if (Init.isInvalid()) {
2292 FD->setInvalidDecl();
2293 return;
2294 }
Richard Smith938f40b2011-06-11 17:19:42 +00002295 }
2296
Richard Smith945f8d32013-01-14 22:39:08 +00002297 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002298 // The initialization of each base and member constitutes a
2299 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002300 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002301 if (Init.isInvalid()) {
2302 FD->setInvalidDecl();
2303 return;
2304 }
2305
2306 InitExpr = Init.release();
2307
2308 FD->setInClassInitializer(InitExpr);
2309}
2310
Douglas Gregor15e77a22009-12-31 09:10:24 +00002311/// \brief Find the direct and/or virtual base specifiers that
2312/// correspond to the given base type, for use in base initialization
2313/// within a constructor.
2314static bool FindBaseInitializer(Sema &SemaRef,
2315 CXXRecordDecl *ClassDecl,
2316 QualType BaseType,
2317 const CXXBaseSpecifier *&DirectBaseSpec,
2318 const CXXBaseSpecifier *&VirtualBaseSpec) {
2319 // First, check for a direct base class.
2320 DirectBaseSpec = 0;
2321 for (CXXRecordDecl::base_class_const_iterator Base
2322 = ClassDecl->bases_begin();
2323 Base != ClassDecl->bases_end(); ++Base) {
2324 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2325 // We found a direct base of this type. That's what we're
2326 // initializing.
2327 DirectBaseSpec = &*Base;
2328 break;
2329 }
2330 }
2331
2332 // Check for a virtual base class.
2333 // FIXME: We might be able to short-circuit this if we know in advance that
2334 // there are no virtual bases.
2335 VirtualBaseSpec = 0;
2336 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2337 // We haven't found a base yet; search the class hierarchy for a
2338 // virtual base class.
2339 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2340 /*DetectVirtual=*/false);
2341 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2342 BaseType, Paths)) {
2343 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2344 Path != Paths.end(); ++Path) {
2345 if (Path->back().Base->isVirtual()) {
2346 VirtualBaseSpec = Path->back().Base;
2347 break;
2348 }
2349 }
2350 }
2351 }
2352
2353 return DirectBaseSpec || VirtualBaseSpec;
2354}
2355
Sebastian Redla74948d2011-09-24 17:48:25 +00002356/// \brief Handle a C++ member initializer using braced-init-list syntax.
2357MemInitResult
2358Sema::ActOnMemInitializer(Decl *ConstructorD,
2359 Scope *S,
2360 CXXScopeSpec &SS,
2361 IdentifierInfo *MemberOrBase,
2362 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002363 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002364 SourceLocation IdLoc,
2365 Expr *InitList,
2366 SourceLocation EllipsisLoc) {
2367 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002368 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002369 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002370}
2371
2372/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002373MemInitResult
John McCall48871652010-08-21 09:40:31 +00002374Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002375 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002376 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002377 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002378 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002379 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002380 SourceLocation IdLoc,
2381 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002382 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002383 SourceLocation RParenLoc,
2384 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002385 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002386 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002387 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002388 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002389}
2390
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002391namespace {
2392
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002393// Callback to only accept typo corrections that can be a valid C++ member
2394// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002395class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002396public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002397 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2398 : ClassDecl(ClassDecl) {}
2399
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002400 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002401 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2402 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2403 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002404 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002405 }
2406 return false;
2407 }
2408
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002409private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002410 CXXRecordDecl *ClassDecl;
2411};
2412
2413}
2414
Sebastian Redla74948d2011-09-24 17:48:25 +00002415/// \brief Handle a C++ member initializer.
2416MemInitResult
2417Sema::BuildMemInitializer(Decl *ConstructorD,
2418 Scope *S,
2419 CXXScopeSpec &SS,
2420 IdentifierInfo *MemberOrBase,
2421 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002422 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002423 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002424 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002425 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002426 if (!ConstructorD)
2427 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002428
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002429 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002430
2431 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002432 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002433 if (!Constructor) {
2434 // The user wrote a constructor initializer on a function that is
2435 // not a C++ constructor. Ignore the error for now, because we may
2436 // have more member initializers coming; we'll diagnose it just
2437 // once in ActOnMemInitializers.
2438 return true;
2439 }
2440
2441 CXXRecordDecl *ClassDecl = Constructor->getParent();
2442
2443 // C++ [class.base.init]p2:
2444 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002445 // constructor's class and, if not found in that scope, are looked
2446 // up in the scope containing the constructor's definition.
2447 // [Note: if the constructor's class contains a member with the
2448 // same name as a direct or virtual base class of the class, a
2449 // mem-initializer-id naming the member or base class and composed
2450 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002451 // mem-initializer-id for the hidden base class may be specified
2452 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002453 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002454 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002455 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002456 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002457 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002458 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002459 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2460 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002461 if (EllipsisLoc.isValid())
2462 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002463 << MemberOrBase
2464 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002465
Sebastian Redla9351792012-02-11 23:51:47 +00002466 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002467 }
Francois Pichetd583da02010-12-04 09:14:42 +00002468 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002469 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002470 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002471 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002472 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002473
2474 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002475 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002476 } else if (DS.getTypeSpecType() == TST_decltype) {
2477 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002478 } else {
2479 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2480 LookupParsedName(R, S, &SS);
2481
2482 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2483 if (!TyD) {
2484 if (R.isAmbiguous()) return true;
2485
John McCallda6841b2010-04-09 19:01:14 +00002486 // We don't want access-control diagnostics here.
2487 R.suppressDiagnostics();
2488
Douglas Gregora3b624a2010-01-19 06:46:48 +00002489 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2490 bool NotUnknownSpecialization = false;
2491 DeclContext *DC = computeDeclContext(SS, false);
2492 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2493 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2494
2495 if (!NotUnknownSpecialization) {
2496 // When the scope specifier can refer to a member of an unknown
2497 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002498 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2499 SS.getWithLocInContext(Context),
2500 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002501 if (BaseType.isNull())
2502 return true;
2503
Douglas Gregora3b624a2010-01-19 06:46:48 +00002504 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002505 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002506 }
2507 }
2508
Douglas Gregor15e77a22009-12-31 09:10:24 +00002509 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002510 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002511 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002512 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002513 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002514 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002515 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002516 // We have found a non-static data member with a similar
2517 // name to what was typed; complain and initialize that
2518 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002519 diagnoseTypo(Corr,
2520 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2521 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002522 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002523 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002524 const CXXBaseSpecifier *DirectBaseSpec;
2525 const CXXBaseSpecifier *VirtualBaseSpec;
2526 if (FindBaseInitializer(*this, ClassDecl,
2527 Context.getTypeDeclType(Type),
2528 DirectBaseSpec, VirtualBaseSpec)) {
2529 // We have found a direct or virtual base class with a
2530 // similar name to what was typed; complain and initialize
2531 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002532 diagnoseTypo(Corr,
2533 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2534 << MemberOrBase << false,
2535 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002536
Richard Smithf9b15102013-08-17 00:46:16 +00002537 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2538 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002539 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002540 diag::note_base_class_specified_here)
2541 << BaseSpec->getType()
2542 << BaseSpec->getSourceRange();
2543
Douglas Gregor15e77a22009-12-31 09:10:24 +00002544 TyD = Type;
2545 }
2546 }
2547 }
2548
Douglas Gregora3b624a2010-01-19 06:46:48 +00002549 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002550 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002551 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002552 return true;
2553 }
John McCallb5a0d312009-12-21 10:41:20 +00002554 }
2555
Douglas Gregora3b624a2010-01-19 06:46:48 +00002556 if (BaseType.isNull()) {
2557 BaseType = Context.getTypeDeclType(TyD);
2558 if (SS.isSet()) {
2559 NestedNameSpecifier *Qualifier =
2560 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00002561
Douglas Gregora3b624a2010-01-19 06:46:48 +00002562 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00002563 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002564 }
John McCallb5a0d312009-12-21 10:41:20 +00002565 }
2566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
John McCallbcd03502009-12-07 02:54:59 +00002568 if (!TInfo)
2569 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002570
Sebastian Redla9351792012-02-11 23:51:47 +00002571 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002572}
2573
Chandler Carruth599deef2011-09-03 01:14:15 +00002574/// Checks a member initializer expression for cases where reference (or
2575/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002576static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2577 Expr *Init,
2578 SourceLocation IdLoc) {
2579 QualType MemberTy = Member->getType();
2580
2581 // We only handle pointers and references currently.
2582 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2583 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2584 return;
2585
2586 const bool IsPointer = MemberTy->isPointerType();
2587 if (IsPointer) {
2588 if (const UnaryOperator *Op
2589 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2590 // The only case we're worried about with pointers requires taking the
2591 // address.
2592 if (Op->getOpcode() != UO_AddrOf)
2593 return;
2594
2595 Init = Op->getSubExpr();
2596 } else {
2597 // We only handle address-of expression initializers for pointers.
2598 return;
2599 }
2600 }
2601
Richard Smithe3b28bc2013-06-12 21:51:50 +00002602 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002603 // We only warn when referring to a non-reference parameter declaration.
2604 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2605 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002606 return;
2607
2608 S.Diag(Init->getExprLoc(),
2609 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2610 : diag::warn_bind_ref_member_to_parameter)
2611 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002612 } else {
2613 // Other initializers are fine.
2614 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002615 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002616
2617 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2618 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002619}
2620
John McCallfaf5fb42010-08-26 23:41:50 +00002621MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002622Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002623 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002624 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2625 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2626 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002627 "Member must be a FieldDecl or IndirectFieldDecl");
2628
Sebastian Redla9351792012-02-11 23:51:47 +00002629 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002630 return true;
2631
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002632 if (Member->isInvalidDecl())
2633 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002634
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002635 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002636 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002637 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002638 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002639 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002640 } else {
2641 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002642 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002643 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002644
Sebastian Redla9351792012-02-11 23:51:47 +00002645 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002646
Sebastian Redla9351792012-02-11 23:51:47 +00002647 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002648 // Can't check initialization for a member of dependent type or when
2649 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002650 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002651 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002652 bool InitList = false;
2653 if (isa<InitListExpr>(Init)) {
2654 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002655 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002656 }
2657
Chandler Carruthd44c3102010-12-06 09:23:57 +00002658 // Initialize the member.
2659 InitializedEntity MemberEntity =
2660 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2661 : InitializedEntity::InitializeMember(IndirectMember, 0);
2662 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002663 InitList ? InitializationKind::CreateDirectList(IdLoc)
2664 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2665 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002666
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002667 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2668 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002669 if (MemberInit.isInvalid())
2670 return true;
2671
Richard Smith736a9472013-06-12 20:42:33 +00002672 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2673
Richard Smith945f8d32013-01-14 22:39:08 +00002674 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002675 // The initialization of each base and member constitutes a
2676 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002677 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002678 if (MemberInit.isInvalid())
2679 return true;
2680
Richard Smithd59b8322012-12-19 01:39:02 +00002681 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002682 }
2683
Chandler Carruthd44c3102010-12-06 09:23:57 +00002684 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002685 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2686 InitRange.getBegin(), Init,
2687 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002688 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002689 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2690 InitRange.getBegin(), Init,
2691 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002692 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002693}
2694
John McCallfaf5fb42010-08-26 23:41:50 +00002695MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002696Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002697 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002698 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002699 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002700 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002701 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002702 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002703
Sebastian Redl0501c632012-02-12 16:37:36 +00002704 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002705 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002706 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2707 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002708 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002709 }
2710
Sebastian Redla9351792012-02-11 23:51:47 +00002711 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002712 // Initialize the object.
2713 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2714 QualType(ClassDecl->getTypeForDecl(), 0));
2715 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002716 InitList ? InitializationKind::CreateDirectList(NameLoc)
2717 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2718 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002719 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002720 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002721 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002722 if (DelegationInit.isInvalid())
2723 return true;
2724
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002725 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2726 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002727
Richard Smith945f8d32013-01-14 22:39:08 +00002728 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002729 // The initialization of each base and member constitutes a
2730 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002731 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2732 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002733 if (DelegationInit.isInvalid())
2734 return true;
2735
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002736 // If we are in a dependent context, template instantiation will
2737 // perform this type-checking again. Just save the arguments that we
2738 // received in a ParenListExpr.
2739 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2740 // of the information that we have about the base
2741 // initializer. However, deconstructing the ASTs is a dicey process,
2742 // and this approach is far more likely to get the corner cases right.
2743 if (CurContext->isDependentContext())
2744 DelegationInit = Owned(Init);
2745
Sebastian Redla9351792012-02-11 23:51:47 +00002746 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002747 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002748 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002749}
2750
2751MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002752Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002753 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002754 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002755 SourceLocation BaseLoc
2756 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002757
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002758 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2759 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2760 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2761
2762 // C++ [class.base.init]p2:
2763 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002764 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002765 // of that class, the mem-initializer is ill-formed. A
2766 // mem-initializer-list can initialize a base class using any
2767 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002768 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002769
Sebastian Redla9351792012-02-11 23:51:47 +00002770 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002771 if (EllipsisLoc.isValid()) {
2772 // This is a pack expansion.
2773 if (!BaseType->containsUnexpandedParameterPack()) {
2774 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002775 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002776
Douglas Gregor44e7df62011-01-04 00:32:56 +00002777 EllipsisLoc = SourceLocation();
2778 }
2779 } else {
2780 // Check for any unexpanded parameter packs.
2781 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2782 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002783
Sebastian Redla9351792012-02-11 23:51:47 +00002784 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002785 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002786 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002787
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002788 // Check for direct and virtual base classes.
2789 const CXXBaseSpecifier *DirectBaseSpec = 0;
2790 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2791 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002792 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2793 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002794 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002795
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002796 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2797 VirtualBaseSpec);
2798
2799 // C++ [base.class.init]p2:
2800 // Unless the mem-initializer-id names a nonstatic data member of the
2801 // constructor's class or a direct or virtual base of that class, the
2802 // mem-initializer is ill-formed.
2803 if (!DirectBaseSpec && !VirtualBaseSpec) {
2804 // If the class has any dependent bases, then it's possible that
2805 // one of those types will resolve to the same type as
2806 // BaseType. Therefore, just treat this as a dependent base
2807 // class initialization. FIXME: Should we try to check the
2808 // initialization anyway? It seems odd.
2809 if (ClassDecl->hasAnyDependentBases())
2810 Dependent = true;
2811 else
2812 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2813 << BaseType << Context.getTypeDeclType(ClassDecl)
2814 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2815 }
2816 }
2817
2818 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002819 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002820
Sebastian Redla74948d2011-09-24 17:48:25 +00002821 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2822 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002823 InitRange.getBegin(), Init,
2824 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002825 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002826
2827 // C++ [base.class.init]p2:
2828 // If a mem-initializer-id is ambiguous because it designates both
2829 // a direct non-virtual base class and an inherited virtual base
2830 // class, the mem-initializer is ill-formed.
2831 if (DirectBaseSpec && VirtualBaseSpec)
2832 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002833 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002834
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002835 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002836 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002837 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002838
2839 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002840 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002841 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002842 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002843 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002844 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002845 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002846
2847 InitializedEntity BaseEntity =
2848 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2849 InitializationKind Kind =
2850 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2851 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2852 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002853 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2854 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002855 if (BaseInit.isInvalid())
2856 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002857
Richard Smith945f8d32013-01-14 22:39:08 +00002858 // C++11 [class.base.init]p7:
2859 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002860 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002861 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002862 if (BaseInit.isInvalid())
2863 return true;
2864
2865 // If we are in a dependent context, template instantiation will
2866 // perform this type-checking again. Just save the arguments that we
2867 // received in a ParenListExpr.
2868 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2869 // of the information that we have about the base
2870 // initializer. However, deconstructing the ASTs is a dicey process,
2871 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002872 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002873 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002874
Alexis Hunt1d792652011-01-08 20:30:50 +00002875 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002876 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002877 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002878 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002879 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002880}
2881
Sebastian Redl22653ba2011-08-30 19:58:05 +00002882// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002883static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2884 if (T.isNull()) T = E->getType();
2885 QualType TargetType = SemaRef.BuildReferenceType(
2886 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002887 SourceLocation ExprLoc = E->getLocStart();
2888 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2889 TargetType, ExprLoc);
2890
2891 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2892 SourceRange(ExprLoc, ExprLoc),
2893 E->getSourceRange()).take();
2894}
2895
Anders Carlsson1b00e242010-04-23 03:10:23 +00002896/// ImplicitInitializerKind - How an implicit base or member initializer should
2897/// initialize its base or member.
2898enum ImplicitInitializerKind {
2899 IIK_Default,
2900 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002901 IIK_Move,
2902 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002903};
2904
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002905static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002906BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002907 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002908 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002909 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002910 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002911 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002912 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2913 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002914
John McCalldadc5752010-08-24 06:29:42 +00002915 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002916
2917 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00002918 case IIK_Inherit: {
2919 const CXXRecordDecl *Inherited =
2920 Constructor->getInheritedConstructor()->getParent();
2921 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2922 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2923 // C++11 [class.inhctor]p8:
2924 // Each expression in the expression-list is of the form
2925 // static_cast<T&&>(p), where p is the name of the corresponding
2926 // constructor parameter and T is the declared type of p.
2927 SmallVector<Expr*, 16> Args;
2928 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2929 ParmVarDecl *PD = Constructor->getParamDecl(I);
2930 ExprResult ArgExpr =
2931 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2932 VK_LValue, SourceLocation());
2933 if (ArgExpr.isInvalid())
2934 return true;
2935 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2936 }
2937
2938 InitializationKind InitKind = InitializationKind::CreateDirect(
2939 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002940 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00002941 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2942 break;
2943 }
2944 }
2945 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00002946 case IIK_Default: {
2947 InitializationKind InitKind
2948 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00002949 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2950 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002951 break;
2952 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002953
Sebastian Redl22653ba2011-08-30 19:58:05 +00002954 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002955 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002956 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002957 ParmVarDecl *Param = Constructor->getParamDecl(0);
2958 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002959
Anders Carlsson1b00e242010-04-23 03:10:23 +00002960 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002961 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00002962 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00002963 Constructor->getLocation(), ParamType,
2964 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002965
Eli Friedmanfa0df832012-02-02 03:46:19 +00002966 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2967
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002968 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002969 QualType ArgTy =
2970 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2971 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002972
Sebastian Redl22653ba2011-08-30 19:58:05 +00002973 if (Moving) {
2974 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2975 }
2976
John McCallcf142162010-08-07 06:22:56 +00002977 CXXCastPath BasePath;
2978 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002979 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2980 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002981 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002982 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002983
Anders Carlsson1b00e242010-04-23 03:10:23 +00002984 InitializationKind InitKind
2985 = InitializationKind::CreateDirect(Constructor->getLocation(),
2986 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002987 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2988 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002989 break;
2990 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002991 }
John McCallb268a282010-08-23 23:25:46 +00002992
Douglas Gregora40433a2010-12-07 00:41:46 +00002993 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002994 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002995 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002996
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002997 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002998 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002999 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3000 SourceLocation()),
3001 BaseSpec->isVirtual(),
3002 SourceLocation(),
3003 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003004 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003005 SourceLocation());
3006
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003007 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003008}
3009
Sebastian Redl22653ba2011-08-30 19:58:05 +00003010static bool RefersToRValueRef(Expr *MemRef) {
3011 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3012 return Referenced->getType()->isRValueReferenceType();
3013}
3014
Anders Carlsson3c1db572010-04-23 02:15:47 +00003015static bool
3016BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003017 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003018 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003019 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003020 if (Field->isInvalidDecl())
3021 return true;
3022
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003023 SourceLocation Loc = Constructor->getLocation();
3024
Sebastian Redl22653ba2011-08-30 19:58:05 +00003025 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3026 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003027 ParmVarDecl *Param = Constructor->getParamDecl(0);
3028 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003029
3030 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003031 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3032 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003033
Anders Carlsson423f5d82010-04-23 16:04:08 +00003034 Expr *MemberExprBase =
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 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003038
Eli Friedmanfa0df832012-02-02 03:46:19 +00003039 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3040
Sebastian Redl22653ba2011-08-30 19:58:05 +00003041 if (Moving) {
3042 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3043 }
3044
Douglas Gregor94f9a482010-05-05 05:51:00 +00003045 // Build a reference to this field within the parameter.
3046 CXXScopeSpec SS;
3047 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3048 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3050 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003051 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003052 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003053 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003054 ParamType, Loc,
3055 /*IsArrow=*/false,
3056 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003057 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003058 /*FirstQualifierInScope=*/0,
3059 MemberLookup,
3060 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003061 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003062 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003063
3064 // C++11 [class.copy]p15:
3065 // - if a member m has rvalue reference type T&&, it is direct-initialized
3066 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003067 if (RefersToRValueRef(CtorArg.get())) {
3068 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003069 }
3070
Douglas Gregor94f9a482010-05-05 05:51:00 +00003071 // When the field we are copying is an array, create index variables for
3072 // each dimension of the array. We use these index variables to subscript
3073 // the source array, and other clients (e.g., CodeGen) will perform the
3074 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003075 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003076 QualType BaseType = Field->getType();
3077 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003078 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003079 while (const ConstantArrayType *Array
3080 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003081 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003082 // Create the iteration variable for this array index.
3083 IdentifierInfo *IterationVarName = 0;
3084 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003085 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003086 llvm::raw_svector_ostream OS(Str);
3087 OS << "__i" << IndexVariables.size();
3088 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3089 }
3090 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003091 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003092 IterationVarName, SizeType,
3093 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003094 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003095 IndexVariables.push_back(IterationVar);
3096
3097 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003098 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003099 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003100 assert(!IterationVarRef.isInvalid() &&
3101 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003102 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3103 assert(!IterationVarRef.isInvalid() &&
3104 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003105
Douglas Gregor94f9a482010-05-05 05:51:00 +00003106 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003107 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003108 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003109 Loc);
3110 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003111 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003112
Douglas Gregor94f9a482010-05-05 05:51:00 +00003113 BaseType = Array->getElementType();
3114 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003115
3116 // The array subscript expression is an lvalue, which is wrong for moving.
3117 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003118 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119
Douglas Gregor94f9a482010-05-05 05:51:00 +00003120 // Construct the entity that we will be initializing. For an array, this
3121 // will be first element in the array, which may require several levels
3122 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003123 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003124 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003125 if (Indirect)
3126 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3127 else
3128 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003129 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3130 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3131 0,
3132 Entities.back()));
3133
3134 // Direct-initialize to use the copy constructor.
3135 InitializationKind InitKind =
3136 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3137
Sebastian Redle9c4e842011-09-04 18:14:28 +00003138 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003139 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003140
John McCalldadc5752010-08-24 06:29:42 +00003141 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003142 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003144 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003145 if (MemberInit.isInvalid())
3146 return true;
3147
Douglas Gregor493627b2011-08-10 15:22:55 +00003148 if (Indirect) {
3149 assert(IndexVariables.size() == 0 &&
3150 "Indirect field improperly initialized");
3151 CXXMemberInit
3152 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3153 Loc, Loc,
3154 MemberInit.takeAs<Expr>(),
3155 Loc);
3156 } else
3157 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3158 Loc, MemberInit.takeAs<Expr>(),
3159 Loc,
3160 IndexVariables.data(),
3161 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003162 return false;
3163 }
3164
Richard Smithc2bc61b2013-03-18 21:12:30 +00003165 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3166 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003167
Anders Carlsson3c1db572010-04-23 02:15:47 +00003168 QualType FieldBaseElementType =
3169 SemaRef.Context.getBaseElementType(Field->getType());
3170
Anders Carlsson3c1db572010-04-23 02:15:47 +00003171 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003172 InitializedEntity InitEntity
3173 = Indirect? InitializedEntity::InitializeMember(Indirect)
3174 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003175 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003176 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003177
3178 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3179 ExprResult MemberInit =
3180 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003181
Douglas Gregora40433a2010-12-07 00:41:46 +00003182 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003183 if (MemberInit.isInvalid())
3184 return true;
3185
Douglas Gregor493627b2011-08-10 15:22:55 +00003186 if (Indirect)
3187 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3188 Indirect, Loc,
3189 Loc,
3190 MemberInit.get(),
3191 Loc);
3192 else
3193 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3194 Field, Loc, Loc,
3195 MemberInit.get(),
3196 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003197 return false;
3198 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003199
Alexis Hunt8b455182011-05-17 00:19:05 +00003200 if (!Field->getParent()->isUnion()) {
3201 if (FieldBaseElementType->isReferenceType()) {
3202 SemaRef.Diag(Constructor->getLocation(),
3203 diag::err_uninitialized_member_in_ctor)
3204 << (int)Constructor->isImplicit()
3205 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3206 << 0 << Field->getDeclName();
3207 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3208 return true;
3209 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003210
Alexis Hunt8b455182011-05-17 00:19:05 +00003211 if (FieldBaseElementType.isConstQualified()) {
3212 SemaRef.Diag(Constructor->getLocation(),
3213 diag::err_uninitialized_member_in_ctor)
3214 << (int)Constructor->isImplicit()
3215 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3216 << 1 << Field->getDeclName();
3217 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3218 return true;
3219 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003220 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003221
David Blaikiebbafb8a2012-03-11 07:00:24 +00003222 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003223 FieldBaseElementType->isObjCRetainableType() &&
3224 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3225 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003226 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003227 // Default-initialize Objective-C pointers to NULL.
3228 CXXMemberInit
3229 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3230 Loc, Loc,
3231 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3232 Loc);
3233 return false;
3234 }
3235
Anders Carlsson3c1db572010-04-23 02:15:47 +00003236 // Nothing to initialize.
3237 CXXMemberInit = 0;
3238 return false;
3239}
John McCallbc83b3f2010-05-20 23:23:51 +00003240
3241namespace {
3242struct BaseAndFieldInfo {
3243 Sema &S;
3244 CXXConstructorDecl *Ctor;
3245 bool AnyErrorsInInits;
3246 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003247 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003248 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003249
3250 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3251 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003252 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3253 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003254 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003255 else if (Generated && Ctor->isMoveConstructor())
3256 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003257 else if (Ctor->getInheritedConstructor())
3258 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003259 else
3260 IIK = IIK_Default;
3261 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003262
3263 bool isImplicitCopyOrMove() const {
3264 switch (IIK) {
3265 case IIK_Copy:
3266 case IIK_Move:
3267 return true;
3268
3269 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003270 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003271 return false;
3272 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003273
3274 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003275 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003276
3277 bool addFieldInitializer(CXXCtorInitializer *Init) {
3278 AllToInit.push_back(Init);
3279
3280 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003281 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003282 S.UnusedPrivateFields.remove(Init->getAnyMember());
3283
3284 return false;
3285 }
John McCallbc83b3f2010-05-20 23:23:51 +00003286};
3287}
3288
Richard Smithc94ec842011-09-19 13:34:43 +00003289/// \brief Determine whether the given indirect field declaration is somewhere
3290/// within an anonymous union.
3291static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3292 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3293 CEnd = F->chain_end();
3294 C != CEnd; ++C)
3295 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3296 if (Record->isUnion())
3297 return true;
3298
3299 return false;
3300}
3301
Douglas Gregor10f939c2011-11-02 23:04:16 +00003302/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3303/// array type.
3304static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3305 if (T->isIncompleteArrayType())
3306 return true;
3307
3308 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3309 if (!ArrayT->getSize())
3310 return true;
3311
3312 T = ArrayT->getElementType();
3313 }
3314
3315 return false;
3316}
3317
Richard Smith938f40b2011-06-11 17:19:42 +00003318static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003319 FieldDecl *Field,
3320 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003321 if (Field->isInvalidDecl())
3322 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003323
Chandler Carruth139e9622010-06-30 02:59:29 +00003324 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003325 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3326 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003327
Richard Smith0a8cfc72012-08-07 21:30:42 +00003328 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith938f40b2011-06-11 17:19:42 +00003329 // has a brace-or-equal-initializer, the entity is initialized as specified
3330 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00003331 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003332 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3333 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003334 CXXCtorInitializer *Init;
3335 if (Indirect)
3336 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3337 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003338 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003339 SourceLocation());
3340 else
3341 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3342 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003343 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003344 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003345 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003346 }
3347
Richard Smith12d5ed82011-09-18 11:14:50 +00003348 // Don't build an implicit initializer for union members if none was
3349 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00003350 if (Field->getParent()->isUnion() ||
3351 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00003352 return false;
3353
Douglas Gregor10f939c2011-11-02 23:04:16 +00003354 // Don't initialize incomplete or zero-length arrays.
3355 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3356 return false;
3357
John McCallbc83b3f2010-05-20 23:23:51 +00003358 // Don't try to build an implicit initializer if there were semantic
3359 // errors in any of the initializers (and therefore we might be
3360 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003361 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003362 return false;
3363
Alexis Hunt1d792652011-01-08 20:30:50 +00003364 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003365 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3366 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003367 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003368
Richard Smith0a8cfc72012-08-07 21:30:42 +00003369 if (!Init)
3370 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003371
Richard Smith0a8cfc72012-08-07 21:30:42 +00003372 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003373}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003374
3375bool
3376Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3377 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003378 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003379 Constructor->setNumCtorInitializers(1);
3380 CXXCtorInitializer **initializer =
3381 new (Context) CXXCtorInitializer*[1];
3382 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3383 Constructor->setCtorInitializers(initializer);
3384
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003385 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003386 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003387 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3388 }
3389
Alexis Hunte2622992011-05-05 00:05:47 +00003390 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003391
Alexis Hunt61bc1732011-05-01 07:04:31 +00003392 return false;
3393}
Douglas Gregor493627b2011-08-10 15:22:55 +00003394
David Blaikie3fc2f912013-01-17 05:26:25 +00003395bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3396 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003397 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003398 // Just store the initializers as written, they will be checked during
3399 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003400 if (!Initializers.empty()) {
3401 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003402 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003403 new (Context) CXXCtorInitializer*[Initializers.size()];
3404 memcpy(baseOrMemberInitializers, Initializers.data(),
3405 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003406 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003407 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003408
3409 // Let template instantiation know whether we had errors.
3410 if (AnyErrors)
3411 Constructor->setInvalidDecl();
3412
Anders Carlssondb0a9652010-04-02 06:26:44 +00003413 return false;
3414 }
3415
John McCallbc83b3f2010-05-20 23:23:51 +00003416 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003417
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003418 // We need to build the initializer AST according to order of construction
3419 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003420 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003421 if (!ClassDecl)
3422 return true;
3423
Eli Friedman9cf6b592009-11-09 19:20:36 +00003424 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003425
David Blaikie3fc2f912013-01-17 05:26:25 +00003426 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003427 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003428
Anders Carlssondb0a9652010-04-02 06:26:44 +00003429 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003430 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003431 else
Francois Pichetd583da02010-12-04 09:14:42 +00003432 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003433 }
3434
Anders Carlsson43c64af2010-04-21 19:52:01 +00003435 // Keep track of the direct virtual bases.
3436 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3437 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3438 E = ClassDecl->bases_end(); I != E; ++I) {
3439 if (I->isVirtual())
3440 DirectVBases.insert(I);
3441 }
3442
Anders Carlssondb0a9652010-04-02 06:26:44 +00003443 // Push virtual bases before others.
3444 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3445 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3446
Alexis Hunt1d792652011-01-08 20:30:50 +00003447 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003448 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003449 // [class.base.init]p7, per DR257:
3450 // A mem-initializer where the mem-initializer-id names a virtual base
3451 // class is ignored during execution of a constructor of any class that
3452 // is not the most derived class.
3453 if (ClassDecl->isAbstract()) {
3454 // FIXME: Provide a fixit to remove the base specifier. This requires
3455 // tracking the location of the associated comma for a base specifier.
3456 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3457 << VBase->getType() << ClassDecl;
3458 DiagnoseAbstractType(ClassDecl);
3459 }
3460
John McCallbc83b3f2010-05-20 23:23:51 +00003461 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003462 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3463 // [class.base.init]p8, per DR257:
3464 // If a given [...] base class is not named by a mem-initializer-id
3465 // [...] and the entity is not a virtual base class of an abstract
3466 // class, then [...] the entity is default-initialized.
Anders Carlsson43c64af2010-04-21 19:52:01 +00003467 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003468 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003469 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithbc46e432013-07-22 02:56:56 +00003470 VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003471 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003472 HadError = true;
3473 continue;
3474 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003475
John McCallbc83b3f2010-05-20 23:23:51 +00003476 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003477 }
3478 }
Mike Stump11289f42009-09-09 15:08:12 +00003479
John McCallbc83b3f2010-05-20 23:23:51 +00003480 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003481 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3482 E = ClassDecl->bases_end(); Base != E; ++Base) {
3483 // Virtuals are in the virtual base list and already constructed.
3484 if (Base->isVirtual())
3485 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003486
Alexis Hunt1d792652011-01-08 20:30:50 +00003487 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003488 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3489 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003490 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003491 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003492 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003493 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003494 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003495 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003496 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003497 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003498
John McCallbc83b3f2010-05-20 23:23:51 +00003499 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003500 }
3501 }
Mike Stump11289f42009-09-09 15:08:12 +00003502
John McCallbc83b3f2010-05-20 23:23:51 +00003503 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00003504 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3505 MemEnd = ClassDecl->decls_end();
3506 Mem != MemEnd; ++Mem) {
3507 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003508 // C++ [class.bit]p2:
3509 // A declaration for a bit-field that omits the identifier declares an
3510 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3511 // initialized.
3512 if (F->isUnnamedBitfield())
3513 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003514
Sebastian Redl22653ba2011-08-30 19:58:05 +00003515 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003516 // handle anonymous struct/union fields based on their individual
3517 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003518 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003519 continue;
3520
3521 if (CollectFieldInitializer(*this, Info, F))
3522 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003523 continue;
3524 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003525
3526 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003527 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003528 continue;
3529
3530 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3531 if (F->getType()->isIncompleteArrayType()) {
3532 assert(ClassDecl->hasFlexibleArrayMember() &&
3533 "Incomplete array type is not valid");
3534 continue;
3535 }
3536
Douglas Gregor493627b2011-08-10 15:22:55 +00003537 // Initialize each field of an anonymous struct individually.
3538 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3539 HadError = true;
3540
3541 continue;
3542 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003543 }
Mike Stump11289f42009-09-09 15:08:12 +00003544
David Blaikie3fc2f912013-01-17 05:26:25 +00003545 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003546 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003547 Constructor->setNumCtorInitializers(NumInitializers);
3548 CXXCtorInitializer **baseOrMemberInitializers =
3549 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003550 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003551 NumInitializers * sizeof(CXXCtorInitializer*));
3552 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003553
John McCalla6309952010-03-16 21:39:52 +00003554 // Constructors implicitly reference the base and member
3555 // destructors.
3556 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3557 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003558 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003559
3560 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003561}
3562
David Blaikieb61b8152013-01-17 08:49:22 +00003563static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003564 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003565 const RecordDecl *RD = RT->getDecl();
3566 if (RD->isAnonymousStructOrUnion()) {
3567 for (RecordDecl::field_iterator Field = RD->field_begin(),
3568 E = RD->field_end(); Field != E; ++Field)
3569 PopulateKeysForFields(*Field, IdealInits);
3570 return;
3571 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003572 }
David Blaikieb61b8152013-01-17 08:49:22 +00003573 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003574}
3575
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003576static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3577 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003578}
3579
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003580static const void *GetKeyForMember(ASTContext &Context,
3581 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003582 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003583 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003584
David Blaikieb61b8152013-01-17 08:49:22 +00003585 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003586}
3587
David Blaikie3fc2f912013-01-17 05:26:25 +00003588static void DiagnoseBaseOrMemInitializerOrder(
3589 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3590 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003591 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003592 return;
Mike Stump11289f42009-09-09 15:08:12 +00003593
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003594 // Don't check initializers order unless the warning is enabled at the
3595 // location of at least one initializer.
3596 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003597 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003598 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003599 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3600 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003601 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003602 ShouldCheckOrder = true;
3603 break;
3604 }
3605 }
3606 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003607 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003608
John McCallbb7b6582010-04-10 07:37:23 +00003609 // Build the list of bases and members in the order that they'll
3610 // actually be initialized. The explicit initializers should be in
3611 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003612 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003613
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003614 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3615
John McCallbb7b6582010-04-10 07:37:23 +00003616 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003617 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003618 ClassDecl->vbases_begin(),
3619 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003620 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003621
John McCallbb7b6582010-04-10 07:37:23 +00003622 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003623 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003624 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003625 if (Base->isVirtual())
3626 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003627 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003628 }
Mike Stump11289f42009-09-09 15:08:12 +00003629
John McCallbb7b6582010-04-10 07:37:23 +00003630 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003631 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003632 E = ClassDecl->field_end(); Field != E; ++Field) {
3633 if (Field->isUnnamedBitfield())
3634 continue;
3635
David Blaikieb61b8152013-01-17 08:49:22 +00003636 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003637 }
3638
John McCallbb7b6582010-04-10 07:37:23 +00003639 unsigned NumIdealInits = IdealInitKeys.size();
3640 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003641
Alexis Hunt1d792652011-01-08 20:30:50 +00003642 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003643 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003644 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003645 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003646
3647 // Scan forward to try to find this initializer in the idealized
3648 // initializers list.
3649 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3650 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003651 break;
John McCallbb7b6582010-04-10 07:37:23 +00003652
3653 // If we didn't find this initializer, it must be because we
3654 // scanned past it on a previous iteration. That can only
3655 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003656 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003657 Sema::SemaDiagnosticBuilder D =
3658 SemaRef.Diag(PrevInit->getSourceLocation(),
3659 diag::warn_initializer_out_of_order);
3660
Francois Pichetd583da02010-12-04 09:14:42 +00003661 if (PrevInit->isAnyMemberInitializer())
3662 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003663 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003664 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003665
Francois Pichetd583da02010-12-04 09:14:42 +00003666 if (Init->isAnyMemberInitializer())
3667 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003668 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003669 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003670
3671 // Move back to the initializer's location in the ideal list.
3672 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3673 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003674 break;
John McCallbb7b6582010-04-10 07:37:23 +00003675
3676 assert(IdealIndex != NumIdealInits &&
3677 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003678 }
John McCallbb7b6582010-04-10 07:37:23 +00003679
3680 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003681 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003682}
3683
John McCall23eebd92010-04-10 09:28:51 +00003684namespace {
3685bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003686 CXXCtorInitializer *Init,
3687 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003688 if (!PrevInit) {
3689 PrevInit = Init;
3690 return false;
3691 }
3692
Douglas Gregorea306a12013-03-25 23:28:23 +00003693 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003694 S.Diag(Init->getSourceLocation(),
3695 diag::err_multiple_mem_initialization)
3696 << Field->getDeclName()
3697 << Init->getSourceRange();
3698 else {
John McCall424cec92011-01-19 06:33:43 +00003699 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003700 assert(BaseClass && "neither field nor base");
3701 S.Diag(Init->getSourceLocation(),
3702 diag::err_multiple_base_initialization)
3703 << QualType(BaseClass, 0)
3704 << Init->getSourceRange();
3705 }
3706 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3707 << 0 << PrevInit->getSourceRange();
3708
3709 return true;
3710}
3711
Alexis Hunt1d792652011-01-08 20:30:50 +00003712typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003713typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3714
3715bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003716 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003717 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003718 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003719 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003720 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003721
3722 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003723 if (Parent->isUnion()) {
3724 UnionEntry &En = Unions[Parent];
3725 if (En.first && En.first != Child) {
3726 S.Diag(Init->getSourceLocation(),
3727 diag::err_multiple_mem_union_initialization)
3728 << Field->getDeclName()
3729 << Init->getSourceRange();
3730 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3731 << 0 << En.second->getSourceRange();
3732 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003733 }
3734 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003735 En.first = Child;
3736 En.second = Init;
3737 }
David Blaikie0f65d592011-11-17 06:01:57 +00003738 if (!Parent->isAnonymousStructOrUnion())
3739 return false;
John McCall23eebd92010-04-10 09:28:51 +00003740 }
3741
3742 Child = Parent;
3743 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003744 }
John McCall23eebd92010-04-10 09:28:51 +00003745
3746 return false;
3747}
3748}
3749
Richard Trieu3a446ff2013-09-16 21:54:53 +00003750// Diagnose value-uses of fields to initialize themselves, e.g.
3751// foo(foo)
3752// where foo is not also a parameter to the constructor.
Richard Trieu406e65c2013-09-20 03:03:06 +00003753// Also diagnose across field uninitialized use such as
3754// x(y), y(x)
Richard Trieu3a446ff2013-09-16 21:54:53 +00003755// TODO: implement -Wuninitialized and fold this into that framework.
Richard Trieu3a446ff2013-09-16 21:54:53 +00003756static void DiagnoseUnitializedFields(
3757 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3758
3759 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3760 Constructor->getLocation())
3761 == DiagnosticsEngine::Ignored) {
3762 return;
3763 }
3764
Richard Trieu406e65c2013-09-20 03:03:06 +00003765 const CXXRecordDecl *RD = Constructor->getParent();
3766
3767 // Holds fields that are uninitialized.
3768 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3769
3770 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
3771 I != E; ++I) {
3772 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
3773 UninitializedFields.insert(FD);
3774 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
3775 UninitializedFields.insert(IFD->getAnonField());
3776 }
3777 }
3778
3779 // Fields already checked when processing the in class initializers.
3780 llvm::SmallPtrSet<ValueDecl*, 4>
3781 InClassUninitializedFields = UninitializedFields;
3782
3783 for (CXXConstructorDecl::init_const_iterator FieldInit =
3784 Constructor->init_begin(),
Richard Trieu3a446ff2013-09-16 21:54:53 +00003785 FieldInitEnd = Constructor->init_end();
3786 FieldInit != FieldInitEnd; ++FieldInit) {
3787
Richard Trieu406e65c2013-09-20 03:03:06 +00003788 FieldDecl *Field = (*FieldInit)->getAnyMember();
Richard Trieu3a446ff2013-09-16 21:54:53 +00003789 Expr *InitExpr = (*FieldInit)->getInit();
3790
Richard Trieu406e65c2013-09-20 03:03:06 +00003791 if (!Field) {
3792 CheckInitExprContainsUninitializedFields(
3793 SemaRef, InitExpr, 0, UninitializedFields,
3794 false/*WarnOnSelfReference*/);
3795 continue;
Richard Trieu3a446ff2013-09-16 21:54:53 +00003796 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003797
3798 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3799 // This field is initialized with an in-class initailzer. Remove the
3800 // fields already checked to prevent duplicate warnings.
3801 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields;
3802 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator
3803 I = InClassUninitializedFields.begin(),
3804 E = InClassUninitializedFields.end();
3805 I != E; ++I) {
3806 DiffSet.erase(*I);
3807 }
3808 CheckInitExprContainsUninitializedFields(
3809 SemaRef, Default->getExpr(), Field, DiffSet,
3810 DiffSet.count(Field), Constructor);
3811
3812 // Update the unitialized field sets.
3813 CheckInitExprContainsUninitializedFields(
3814 SemaRef, Default->getExpr(), 0, UninitializedFields,
3815 false);
3816 CheckInitExprContainsUninitializedFields(
3817 SemaRef, Default->getExpr(), 0, InClassUninitializedFields,
3818 false);
3819 } else {
3820 CheckInitExprContainsUninitializedFields(
3821 SemaRef, InitExpr, Field, UninitializedFields,
3822 UninitializedFields.count(Field));
3823 if (Expr* InClassInit = Field->getInClassInitializer()) {
3824 CheckInitExprContainsUninitializedFields(
3825 SemaRef, InClassInit, 0, InClassUninitializedFields,
3826 false);
3827 }
3828 }
3829 UninitializedFields.erase(Field);
3830 InClassUninitializedFields.erase(Field);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003831 }
3832}
3833
Anders Carlssone857b292010-04-02 03:37:03 +00003834/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003835void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003836 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003837 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003838 bool AnyErrors) {
3839 if (!ConstructorDecl)
3840 return;
3841
3842 AdjustDeclIfTemplate(ConstructorDecl);
3843
3844 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003845 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003846
3847 if (!Constructor) {
3848 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3849 return;
3850 }
3851
John McCall23eebd92010-04-10 09:28:51 +00003852 // Mapping for the duplicate initializers check.
3853 // For member initializers, this is keyed with a FieldDecl*.
3854 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003855 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003856
3857 // Mapping for the inconsistent anonymous-union initializers check.
3858 RedundantUnionMap MemberUnions;
3859
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003860 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003861 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003862 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003863
Abramo Bagnara341d7832010-05-26 18:09:23 +00003864 // Set the source order index.
3865 Init->setSourceOrder(i);
3866
Francois Pichetd583da02010-12-04 09:14:42 +00003867 if (Init->isAnyMemberInitializer()) {
3868 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003869 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3870 CheckRedundantUnionInit(*this, Init, MemberUnions))
3871 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003872 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003873 const void *Key =
3874 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003875 if (CheckRedundantInit(*this, Init, Members[Key]))
3876 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003877 } else {
3878 assert(Init->isDelegatingInitializer());
3879 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003880 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003881 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003882 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003883 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003884 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003885 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003886 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003887 // Return immediately as the initializer is set.
3888 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003889 }
Anders Carlssone857b292010-04-02 03:37:03 +00003890 }
3891
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003892 if (HadError)
3893 return;
3894
David Blaikie3fc2f912013-01-17 05:26:25 +00003895 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003896
David Blaikie3fc2f912013-01-17 05:26:25 +00003897 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003898
3899 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003900}
3901
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003902void
John McCalla6309952010-03-16 21:39:52 +00003903Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3904 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003905 // Ignore dependent contexts. Also ignore unions, since their members never
3906 // have destructors implicitly called.
3907 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003908 return;
John McCall1064d7e2010-03-16 05:22:47 +00003909
3910 // FIXME: all the access-control diagnostics are positioned on the
3911 // field/base declaration. That's probably good; that said, the
3912 // user might reasonably want to know why the destructor is being
3913 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003914
Anders Carlssondee9a302009-11-17 04:44:12 +00003915 // Non-static data members.
3916 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3917 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003918 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003919 if (Field->isInvalidDecl())
3920 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003921
3922 // Don't destroy incomplete or zero-length arrays.
3923 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3924 continue;
3925
Anders Carlssondee9a302009-11-17 04:44:12 +00003926 QualType FieldType = Context.getBaseElementType(Field->getType());
3927
3928 const RecordType* RT = FieldType->getAs<RecordType>();
3929 if (!RT)
3930 continue;
3931
3932 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003933 if (FieldClassDecl->isInvalidDecl())
3934 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003935 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003936 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003937 // The destructor for an implicit anonymous union member is never invoked.
3938 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3939 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003940
Douglas Gregore71edda2010-07-01 22:47:18 +00003941 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003942 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003943 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003944 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003945 << Field->getDeclName()
3946 << FieldType);
3947
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003948 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003949 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003950 }
3951
John McCall1064d7e2010-03-16 05:22:47 +00003952 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3953
Anders Carlssondee9a302009-11-17 04:44:12 +00003954 // Bases.
3955 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3956 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003957 // Bases are always records in a well-formed non-dependent class.
3958 const RecordType *RT = Base->getType()->getAs<RecordType>();
3959
3960 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003961 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003962 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003963
John McCall1064d7e2010-03-16 05:22:47 +00003964 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003965 // If our base class is invalid, we probably can't get its dtor anyway.
3966 if (BaseClassDecl->isInvalidDecl())
3967 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003968 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003969 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003970
Douglas Gregore71edda2010-07-01 22:47:18 +00003971 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003972 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003973
3974 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003975 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003976 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003977 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00003978 << Base->getSourceRange(),
3979 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00003980
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003981 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003982 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003983 }
3984
3985 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003986 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3987 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003988
3989 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00003990 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00003991
3992 // Ignore direct virtual bases.
3993 if (DirectVirtualBases.count(RT))
3994 continue;
3995
John McCall1064d7e2010-03-16 05:22:47 +00003996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003997 // If our base class is invalid, we probably can't get its dtor anyway.
3998 if (BaseClassDecl->isInvalidDecl())
3999 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004000 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004001 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004002
Douglas Gregore71edda2010-07-01 22:47:18 +00004003 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004004 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004005 if (CheckDestructorAccess(
4006 ClassDecl->getLocation(), Dtor,
4007 PDiag(diag::err_access_dtor_vbase)
4008 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4009 Context.getTypeDeclType(ClassDecl)) ==
4010 AR_accessible) {
4011 CheckDerivedToBaseConversion(
4012 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4013 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4014 SourceRange(), DeclarationName(), 0);
4015 }
John McCall1064d7e2010-03-16 05:22:47 +00004016
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004017 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004018 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004019 }
4020}
4021
John McCall48871652010-08-21 09:40:31 +00004022void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004023 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004024 return;
Mike Stump11289f42009-09-09 15:08:12 +00004025
Mike Stump11289f42009-09-09 15:08:12 +00004026 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004027 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie3fc2f912013-01-17 05:26:25 +00004028 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004029}
4030
Mike Stump11289f42009-09-09 15:08:12 +00004031bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004032 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004033 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4034 unsigned DiagID;
4035 AbstractDiagSelID SelID;
4036
4037 public:
4038 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4039 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004040
4041 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004042 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004043 if (SelID == -1)
4044 S.Diag(Loc, DiagID) << T;
4045 else
4046 S.Diag(Loc, DiagID) << SelID << T;
4047 }
4048 } Diagnoser(DiagID, SelID);
4049
4050 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004051}
4052
Anders Carlssoneabf7702009-08-27 00:13:57 +00004053bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004054 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004055 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004056 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004057
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004058 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004059 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004060
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004061 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004062 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004063 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004064 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004065
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004066 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004067 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004068 }
Mike Stump11289f42009-09-09 15:08:12 +00004069
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004070 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004071 if (!RT)
4072 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004073
John McCall67da35c2010-02-04 22:26:26 +00004074 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004075
John McCall02db245d2010-08-18 09:41:07 +00004076 // We can't answer whether something is abstract until it has a
4077 // definition. If it's currently being defined, we'll walk back
4078 // over all the declarations when we have a full definition.
4079 const CXXRecordDecl *Def = RD->getDefinition();
4080 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004081 return false;
4082
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004083 if (!RD->isAbstract())
4084 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004085
Douglas Gregorae298422012-05-04 17:09:59 +00004086 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004087 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004088
John McCall02db245d2010-08-18 09:41:07 +00004089 return true;
4090}
4091
4092void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4093 // Check if we've already emitted the list of pure virtual functions
4094 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004095 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004096 return;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Richard Smithbc46e432013-07-22 02:56:56 +00004098 // If the diagnostic is suppressed, don't emit the notes. We're only
4099 // going to emit them once, so try to attach them to a diagnostic we're
4100 // actually going to show.
4101 if (Diags.isLastDiagnosticIgnored())
4102 return;
4103
Douglas Gregor4165bd62010-03-23 23:47:56 +00004104 CXXFinalOverriderMap FinalOverriders;
4105 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004106
Anders Carlssona2f74f32010-06-03 01:00:02 +00004107 // Keep a set of seen pure methods so we won't diagnose the same method
4108 // more than once.
4109 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4110
Douglas Gregor4165bd62010-03-23 23:47:56 +00004111 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4112 MEnd = FinalOverriders.end();
4113 M != MEnd;
4114 ++M) {
4115 for (OverridingMethods::iterator SO = M->second.begin(),
4116 SOEnd = M->second.end();
4117 SO != SOEnd; ++SO) {
4118 // C++ [class.abstract]p4:
4119 // A class is abstract if it contains or inherits at least one
4120 // pure virtual function for which the final overrider is pure
4121 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004122
Douglas Gregor4165bd62010-03-23 23:47:56 +00004123 //
4124 if (SO->second.size() != 1)
4125 continue;
4126
4127 if (!SO->second.front().Method->isPure())
4128 continue;
4129
Anders Carlssona2f74f32010-06-03 01:00:02 +00004130 if (!SeenPureMethods.insert(SO->second.front().Method))
4131 continue;
4132
Douglas Gregor4165bd62010-03-23 23:47:56 +00004133 Diag(SO->second.front().Method->getLocation(),
4134 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004135 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004136 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004137 }
4138
4139 if (!PureVirtualClassDiagSet)
4140 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4141 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004142}
4143
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004144namespace {
John McCall02db245d2010-08-18 09:41:07 +00004145struct AbstractUsageInfo {
4146 Sema &S;
4147 CXXRecordDecl *Record;
4148 CanQualType AbstractType;
4149 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004150
John McCall02db245d2010-08-18 09:41:07 +00004151 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4152 : S(S), Record(Record),
4153 AbstractType(S.Context.getCanonicalType(
4154 S.Context.getTypeDeclType(Record))),
4155 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004156
John McCall02db245d2010-08-18 09:41:07 +00004157 void DiagnoseAbstractType() {
4158 if (Invalid) return;
4159 S.DiagnoseAbstractType(Record);
4160 Invalid = true;
4161 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004162
John McCall02db245d2010-08-18 09:41:07 +00004163 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4164};
4165
4166struct CheckAbstractUsage {
4167 AbstractUsageInfo &Info;
4168 const NamedDecl *Ctx;
4169
4170 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4171 : Info(Info), Ctx(Ctx) {}
4172
4173 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4174 switch (TL.getTypeLocClass()) {
4175#define ABSTRACT_TYPELOC(CLASS, PARENT)
4176#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004177 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004178#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004179 }
John McCall02db245d2010-08-18 09:41:07 +00004180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
John McCall02db245d2010-08-18 09:41:07 +00004182 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4183 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4184 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004185 if (!TL.getArg(I))
4186 continue;
4187
John McCall02db245d2010-08-18 09:41:07 +00004188 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4189 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004190 }
John McCall02db245d2010-08-18 09:41:07 +00004191 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004192
John McCall02db245d2010-08-18 09:41:07 +00004193 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4194 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
John McCall02db245d2010-08-18 09:41:07 +00004197 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4198 // Visit the type parameters from a permissive context.
4199 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4200 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4201 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4202 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4203 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4204 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004205 }
John McCall02db245d2010-08-18 09:41:07 +00004206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207
John McCall02db245d2010-08-18 09:41:07 +00004208 // Visit pointee types from a permissive context.
4209#define CheckPolymorphic(Type) \
4210 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4211 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4212 }
4213 CheckPolymorphic(PointerTypeLoc)
4214 CheckPolymorphic(ReferenceTypeLoc)
4215 CheckPolymorphic(MemberPointerTypeLoc)
4216 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004217 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004218
John McCall02db245d2010-08-18 09:41:07 +00004219 /// Handle all the types we haven't given a more specific
4220 /// implementation for above.
4221 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4222 // Every other kind of type that we haven't called out already
4223 // that has an inner type is either (1) sugar or (2) contains that
4224 // inner type in some way as a subobject.
4225 if (TypeLoc Next = TL.getNextTypeLoc())
4226 return Visit(Next, Sel);
4227
4228 // If there's no inner type and we're in a permissive context,
4229 // don't diagnose.
4230 if (Sel == Sema::AbstractNone) return;
4231
4232 // Check whether the type matches the abstract type.
4233 QualType T = TL.getType();
4234 if (T->isArrayType()) {
4235 Sel = Sema::AbstractArrayType;
4236 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004237 }
John McCall02db245d2010-08-18 09:41:07 +00004238 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4239 if (CT != Info.AbstractType) return;
4240
4241 // It matched; do some magic.
4242 if (Sel == Sema::AbstractArrayType) {
4243 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4244 << T << TL.getSourceRange();
4245 } else {
4246 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4247 << Sel << T << TL.getSourceRange();
4248 }
4249 Info.DiagnoseAbstractType();
4250 }
4251};
4252
4253void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4254 Sema::AbstractDiagSelID Sel) {
4255 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4256}
4257
4258}
4259
4260/// Check for invalid uses of an abstract type in a method declaration.
4261static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4262 CXXMethodDecl *MD) {
4263 // No need to do the check on definitions, which require that
4264 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004265 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004266 return;
4267
4268 // For safety's sake, just ignore it if we don't have type source
4269 // information. This should never happen for non-implicit methods,
4270 // but...
4271 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4272 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4273}
4274
4275/// Check for invalid uses of an abstract type within a class definition.
4276static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4277 CXXRecordDecl *RD) {
4278 for (CXXRecordDecl::decl_iterator
4279 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4280 Decl *D = *I;
4281 if (D->isImplicit()) continue;
4282
4283 // Methods and method templates.
4284 if (isa<CXXMethodDecl>(D)) {
4285 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4286 } else if (isa<FunctionTemplateDecl>(D)) {
4287 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4288 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4289
4290 // Fields and static variables.
4291 } else if (isa<FieldDecl>(D)) {
4292 FieldDecl *FD = cast<FieldDecl>(D);
4293 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4294 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4295 } else if (isa<VarDecl>(D)) {
4296 VarDecl *VD = cast<VarDecl>(D);
4297 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4298 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4299
4300 // Nested classes and class templates.
4301 } else if (isa<CXXRecordDecl>(D)) {
4302 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4303 } else if (isa<ClassTemplateDecl>(D)) {
4304 CheckAbstractClassUsage(Info,
4305 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4306 }
4307 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004308}
4309
Douglas Gregorc99f1552009-12-03 18:33:45 +00004310/// \brief Perform semantic checks on a class definition that has been
4311/// completing, introducing implicitly-declared members, checking for
4312/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004313void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004314 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004315 return;
4316
John McCall02db245d2010-08-18 09:41:07 +00004317 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4318 AbstractUsageInfo Info(*this, Record);
4319 CheckAbstractClassUsage(Info, Record);
4320 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004321
4322 // If this is not an aggregate type and has no user-declared constructor,
4323 // complain about any non-static data members of reference or const scalar
4324 // type, since they will never get initializers.
4325 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004326 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4327 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004328 bool Complained = false;
4329 for (RecordDecl::field_iterator F = Record->field_begin(),
4330 FEnd = Record->field_end();
4331 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004332 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004333 continue;
4334
Douglas Gregor454a5b62010-04-15 00:00:53 +00004335 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004336 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004337 if (!Complained) {
4338 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4339 << Record->getTagKind() << Record;
4340 Complained = true;
4341 }
4342
4343 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4344 << F->getType()->isReferenceType()
4345 << F->getDeclName();
4346 }
4347 }
4348 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004349
Anders Carlssone771e762011-01-25 18:08:22 +00004350 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004351 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004352
4353 if (Record->getIdentifier()) {
4354 // C++ [class.mem]p13:
4355 // If T is the name of a class, then each of the following shall have a
4356 // name different from T:
4357 // - every member of every anonymous union that is a member of class T.
4358 //
4359 // C++ [class.mem]p14:
4360 // In addition, if class T has a user-declared constructor (12.1), every
4361 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004362 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4363 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4364 ++I) {
4365 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004366 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4367 isa<IndirectFieldDecl>(D)) {
4368 Diag(D->getLocation(), diag::err_member_name_of_class)
4369 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004370 break;
4371 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004372 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004373 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004374
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004375 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004376 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004377 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004378 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004379 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4380 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4381 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004382
David Blaikie348df502012-09-21 03:21:07 +00004383 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4384 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4385 DiagnoseAbstractType(Record);
4386 }
4387
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004388 if (!Record->isDependentType()) {
4389 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4390 MEnd = Record->method_end();
4391 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004392 // See if a method overloads virtual methods in a base
4393 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004394 if (!M->isStatic())
Eli Friedmanaf65120b2013-09-05 23:51:03 +00004395 DiagnoseHiddenVirtualMethods(*M);
Richard Smithbd305122012-12-11 01:14:52 +00004396
4397 // Check whether the explicitly-defaulted special members are valid.
4398 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4399 CheckExplicitlyDefaultedSpecialMember(*M);
4400
4401 // For an explicitly defaulted or deleted special member, we defer
4402 // determining triviality until the class is complete. That time is now!
4403 if (!M->isImplicit() && !M->isUserProvided()) {
4404 CXXSpecialMember CSM = getSpecialMember(*M);
4405 if (CSM != CXXInvalid) {
4406 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4407
4408 // Inform the class that we've finished declaring this member.
4409 Record->finishedDefaultedOrDeletedMember(*M);
4410 }
4411 }
4412 }
4413 }
4414
4415 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4416 // function that is not a constructor declares that member function to be
4417 // const. [...] The class of which that function is a member shall be
4418 // a literal type.
4419 //
4420 // If the class has virtual bases, any constexpr members will already have
4421 // been diagnosed by the checks performed on the member declaration, so
4422 // suppress this (less useful) diagnostic.
4423 //
4424 // We delay this until we know whether an explicitly-defaulted (or deleted)
4425 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004426 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004427 !Record->isLiteral() && !Record->getNumVBases()) {
4428 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4429 MEnd = Record->method_end();
4430 M != MEnd; ++M) {
4431 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4432 switch (Record->getTemplateSpecializationKind()) {
4433 case TSK_ImplicitInstantiation:
4434 case TSK_ExplicitInstantiationDeclaration:
4435 case TSK_ExplicitInstantiationDefinition:
4436 // If a template instantiates to a non-literal type, but its members
4437 // instantiate to constexpr functions, the template is technically
4438 // ill-formed, but we allow it for sanity.
4439 continue;
4440
4441 case TSK_Undeclared:
4442 case TSK_ExplicitSpecialization:
4443 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4444 diag::err_constexpr_method_non_literal);
4445 break;
4446 }
4447
4448 // Only produce one error per class.
4449 break;
4450 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004451 }
4452 }
Sebastian Redl08905022011-02-05 19:23:19 +00004453
Warren Hunt8f8bad72013-10-11 20:19:00 +00004454 // Check to see if we're trying to lay out a struct using the ms_struct
4455 // attribute that is dynamic.
4456 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4457 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4458 Record->dropAttr<MsStructAttr>();
4459 }
4460
Richard Smithc2bc61b2013-03-18 21:12:30 +00004461 // Declare inheriting constructors. We do this eagerly here because:
4462 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004463 // constructors from different classes.
4464 // - The lazy declaration of the other implicit constructors is so as to not
4465 // waste space and performance on classes that are not meant to be
4466 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004467 // have inheriting constructors.
4468 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004469}
4470
Richard Smithb5800092012-06-10 05:43:50 +00004471/// Is the special member function which would be selected to perform the
4472/// specified operation on the specified class type a constexpr constructor?
4473static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4474 Sema::CXXSpecialMember CSM,
4475 bool ConstArg) {
4476 Sema::SpecialMemberOverloadResult *SMOR =
4477 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4478 false, false, false, false);
4479 if (!SMOR || !SMOR->getMethod())
4480 // A constructor we wouldn't select can't be "involved in initializing"
4481 // anything.
4482 return true;
4483 return SMOR->getMethod()->isConstexpr();
4484}
4485
4486/// Determine whether the specified special member function would be constexpr
4487/// if it were implicitly defined.
4488static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4489 Sema::CXXSpecialMember CSM,
4490 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004491 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004492 return false;
4493
4494 // C++11 [dcl.constexpr]p4:
4495 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004496 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004497 switch (CSM) {
4498 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004499 // Since default constructor lookup is essentially trivial (and cannot
4500 // involve, for instance, template instantiation), we compute whether a
4501 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4502 //
4503 // This is important for performance; we need to know whether the default
4504 // constructor is constexpr to determine whether the type is a literal type.
4505 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4506
Richard Smithb5800092012-06-10 05:43:50 +00004507 case Sema::CXXCopyConstructor:
4508 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004509 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004510 break;
4511
4512 case Sema::CXXCopyAssignment:
4513 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004514 if (!S.getLangOpts().CPlusPlus1y)
4515 return false;
4516 // In C++1y, we need to perform overload resolution.
4517 Ctor = false;
4518 break;
4519
Richard Smithb5800092012-06-10 05:43:50 +00004520 case Sema::CXXDestructor:
4521 case Sema::CXXInvalid:
4522 return false;
4523 }
4524
4525 // -- if the class is a non-empty union, or for each non-empty anonymous
4526 // union member of a non-union class, exactly one non-static data member
4527 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004528 //
4529 // If we squint, this is guaranteed, since exactly one non-static data member
4530 // will be initialized (if the constructor isn't deleted), we just don't know
4531 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004532 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004533 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004534
4535 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004536 if (Ctor && ClassDecl->getNumVBases())
4537 return false;
4538
4539 // C++1y [class.copy]p26:
4540 // -- [the class] is a literal type, and
4541 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004542 return false;
4543
4544 // -- every constructor involved in initializing [...] base class
4545 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004546 // -- the assignment operator selected to copy/move each direct base
4547 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004548 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4549 BEnd = ClassDecl->bases_end();
4550 B != BEnd; ++B) {
4551 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4552 if (!BaseType) continue;
4553
4554 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4555 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4556 return false;
4557 }
4558
4559 // -- every constructor involved in initializing non-static data members
4560 // [...] shall be a constexpr constructor;
4561 // -- every non-static data member and base class sub-object shall be
4562 // initialized
Richard Smith99005e62013-05-07 03:19:20 +00004563 // -- for each non-stastic data member of X that is of class type (or array
4564 // thereof), the assignment operator selected to copy/move that member is
4565 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004566 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4567 FEnd = ClassDecl->field_end();
4568 F != FEnd; ++F) {
4569 if (F->isInvalidDecl())
4570 continue;
Richard Smith4086a132012-06-10 07:07:24 +00004571 if (const RecordType *RecordTy =
4572 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004573 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4574 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4575 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004576 }
4577 }
4578
4579 // All OK, it's constexpr!
4580 return true;
4581}
4582
Richard Smithd3b5c9082012-07-27 04:22:15 +00004583static Sema::ImplicitExceptionSpecification
4584computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4585 switch (S.getSpecialMember(MD)) {
4586 case Sema::CXXDefaultConstructor:
4587 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4588 case Sema::CXXCopyConstructor:
4589 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4590 case Sema::CXXCopyAssignment:
4591 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4592 case Sema::CXXMoveConstructor:
4593 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4594 case Sema::CXXMoveAssignment:
4595 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4596 case Sema::CXXDestructor:
4597 return S.ComputeDefaultedDtorExceptionSpec(MD);
4598 case Sema::CXXInvalid:
4599 break;
4600 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004601 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4602 "only special members have implicit exception specs");
4603 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004604}
4605
Richard Smith7f782272012-07-30 23:48:14 +00004606static void
4607updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4608 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4609 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4610 ExceptSpec.getEPI(EPI);
Richard Smith185be182013-04-10 05:48:59 +00004611 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4612 FPT->getArgTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004613}
4614
Reid Kleckner78af0702013-08-27 23:08:25 +00004615static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4616 CXXMethodDecl *MD) {
4617 FunctionProtoType::ExtProtoInfo EPI;
4618
4619 // Build an exception specification pointing back at this member.
4620 EPI.ExceptionSpecType = EST_Unevaluated;
4621 EPI.ExceptionSpecDecl = MD;
4622
4623 // Set the calling convention to the default for C++ instance methods.
4624 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4625 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4626 /*IsCXXMethod=*/true));
4627 return EPI;
4628}
4629
Richard Smithd3b5c9082012-07-27 04:22:15 +00004630void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4631 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4632 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4633 return;
4634
Richard Smith7f782272012-07-30 23:48:14 +00004635 // Evaluate the exception specification.
4636 ImplicitExceptionSpecification ExceptSpec =
4637 computeImplicitExceptionSpec(*this, Loc, MD);
4638
4639 // Update the type of the special member to use it.
4640 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4641
4642 // A user-provided destructor can be defined outside the class. When that
4643 // happens, be sure to update the exception specification on both
4644 // declarations.
4645 const FunctionProtoType *CanonicalFPT =
4646 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4647 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4648 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4649 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004650}
4651
Richard Smithb9e90b12012-05-15 04:39:51 +00004652void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4653 CXXRecordDecl *RD = MD->getParent();
4654 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004655
Richard Smithb9e90b12012-05-15 04:39:51 +00004656 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4657 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004658
4659 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004660 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004661 bool First = MD == MD->getCanonicalDecl();
4662
4663 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004664
4665 // C++11 [dcl.fct.def.default]p1:
4666 // A function that is explicitly defaulted shall
4667 // -- be a special member function (checked elsewhere),
4668 // -- have the same type (except for ref-qualifiers, and except that a
4669 // copy operation can take a non-const reference) as an implicit
4670 // declaration, and
4671 // -- not have default arguments.
4672 unsigned ExpectedParams = 1;
4673 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4674 ExpectedParams = 0;
4675 if (MD->getNumParams() != ExpectedParams) {
4676 // This also checks for default arguments: a copy or move constructor with a
4677 // default argument is classified as a default constructor, and assignment
4678 // operations and destructors can't have default arguments.
4679 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4680 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004681 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004682 } else if (MD->isVariadic()) {
4683 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4684 << CSM << MD->getSourceRange();
4685 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004686 }
4687
Richard Smithb9e90b12012-05-15 04:39:51 +00004688 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004689
Richard Smithb5800092012-06-10 05:43:50 +00004690 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004691 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004692 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004693 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004694 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004695
Richard Smithb9e90b12012-05-15 04:39:51 +00004696 QualType ReturnType = Context.VoidTy;
4697 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4698 // Check for return type matching.
4699 ReturnType = Type->getResultType();
4700 QualType ExpectedReturnType =
4701 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4702 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4703 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4704 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4705 HadError = true;
4706 }
4707
4708 // A defaulted special member cannot have cv-qualifiers.
4709 if (Type->getTypeQuals()) {
4710 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004711 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004712 HadError = true;
4713 }
4714 }
4715
4716 // Check for parameter type matching.
4717 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004718 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004719 if (ExpectedParams && ArgType->isReferenceType()) {
4720 // Argument must be reference to possibly-const T.
4721 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004722 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004723
4724 if (ReferentType.isVolatileQualified()) {
4725 Diag(MD->getLocation(),
4726 diag::err_defaulted_special_member_volatile_param) << CSM;
4727 HadError = true;
4728 }
4729
Richard Smithb5800092012-06-10 05:43:50 +00004730 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004731 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4732 Diag(MD->getLocation(),
4733 diag::err_defaulted_special_member_copy_const_param)
4734 << (CSM == CXXCopyAssignment);
4735 // FIXME: Explain why this special member can't be const.
4736 } else {
4737 Diag(MD->getLocation(),
4738 diag::err_defaulted_special_member_move_const_param)
4739 << (CSM == CXXMoveAssignment);
4740 }
4741 HadError = true;
4742 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004743 } else if (ExpectedParams) {
4744 // A copy assignment operator can take its argument by value, but a
4745 // defaulted one cannot.
4746 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004747 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004748 HadError = true;
4749 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004750
Richard Smithcc36f692011-12-22 02:22:31 +00004751 // C++11 [dcl.fct.def.default]p2:
4752 // An explicitly-defaulted function may be declared constexpr only if it
4753 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004754 // Do not apply this rule to members of class templates, since core issue 1358
4755 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004756 // functions which cannot be constexpr (for non-constructors in C++11 and for
4757 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004758 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4759 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004760 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4761 : isa<CXXConstructorDecl>(MD)) &&
4762 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004763 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4764 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004765 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004766 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004767 }
Richard Smithbd305122012-12-11 01:14:52 +00004768
Richard Smithcc36f692011-12-22 02:22:31 +00004769 // and may have an explicit exception-specification only if it is compatible
4770 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004771 if (Type->hasExceptionSpec()) {
4772 // Delay the check if this is the first declaration of the special member,
4773 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004774 if (First) {
4775 // If the exception specification needs to be instantiated, do so now,
4776 // before we clobber it with an EST_Unevaluated specification below.
4777 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4778 InstantiateExceptionSpec(MD->getLocStart(), MD);
4779 Type = MD->getType()->getAs<FunctionProtoType>();
4780 }
Richard Smithbd305122012-12-11 01:14:52 +00004781 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004782 } else
Richard Smithbd305122012-12-11 01:14:52 +00004783 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4784 }
Richard Smithcc36f692011-12-22 02:22:31 +00004785
4786 // If a function is explicitly defaulted on its first declaration,
4787 if (First) {
4788 // -- it is implicitly considered to be constexpr if the implicit
4789 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004790 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004791
Richard Smithb9e90b12012-05-15 04:39:51 +00004792 // -- it is implicitly considered to have the same exception-specification
4793 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004794 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4795 EPI.ExceptionSpecType = EST_Unevaluated;
4796 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004797 MD->setType(Context.getFunctionType(ReturnType,
4798 ArrayRef<QualType>(&ArgType,
4799 ExpectedParams),
4800 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004801 }
4802
Richard Smithb9e90b12012-05-15 04:39:51 +00004803 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004804 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004805 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004806 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004807 // C++11 [dcl.fct.def.default]p4:
4808 // [For a] user-provided explicitly-defaulted function [...] if such a
4809 // function is implicitly defined as deleted, the program is ill-formed.
4810 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4811 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004812 }
4813 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004814
Richard Smithb9e90b12012-05-15 04:39:51 +00004815 if (HadError)
4816 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004817}
4818
Richard Smithbd305122012-12-11 01:14:52 +00004819/// Check whether the exception specification provided for an
4820/// explicitly-defaulted special member matches the exception specification
4821/// that would have been generated for an implicit special member, per
4822/// C++11 [dcl.fct.def.default]p2.
4823void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4824 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4825 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004826 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4827 /*IsCXXMethod=*/true);
4828 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004829 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4830 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004831 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004832
4833 // Ensure that it matches.
4834 CheckEquivalentExceptionSpec(
4835 PDiag(diag::err_incorrect_defaulted_exception_spec)
4836 << getSpecialMember(MD), PDiag(),
4837 ImplicitType, SourceLocation(),
4838 SpecifiedType, MD->getLocation());
4839}
4840
4841void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4842 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4843 I != N; ++I)
4844 CheckExplicitlyDefaultedMemberExceptionSpec(
4845 DelayedDefaultedMemberExceptionSpecs[I].first,
4846 DelayedDefaultedMemberExceptionSpecs[I].second);
4847
4848 DelayedDefaultedMemberExceptionSpecs.clear();
4849}
4850
Richard Smithd951a1d2012-02-18 02:02:13 +00004851namespace {
4852struct SpecialMemberDeletionInfo {
4853 Sema &S;
4854 CXXMethodDecl *MD;
4855 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004856 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004857
4858 // Properties of the special member, computed for convenience.
4859 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4860 SourceLocation Loc;
4861
4862 bool AllFieldsAreConst;
4863
4864 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004865 Sema::CXXSpecialMember CSM, bool Diagnose)
4866 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004867 IsConstructor(false), IsAssignment(false), IsMove(false),
4868 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4869 AllFieldsAreConst(true) {
4870 switch (CSM) {
4871 case Sema::CXXDefaultConstructor:
4872 case Sema::CXXCopyConstructor:
4873 IsConstructor = true;
4874 break;
4875 case Sema::CXXMoveConstructor:
4876 IsConstructor = true;
4877 IsMove = true;
4878 break;
4879 case Sema::CXXCopyAssignment:
4880 IsAssignment = true;
4881 break;
4882 case Sema::CXXMoveAssignment:
4883 IsAssignment = true;
4884 IsMove = true;
4885 break;
4886 case Sema::CXXDestructor:
4887 break;
4888 case Sema::CXXInvalid:
4889 llvm_unreachable("invalid special member kind");
4890 }
4891
4892 if (MD->getNumParams()) {
4893 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4894 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4895 }
4896 }
4897
4898 bool inUnion() const { return MD->getParent()->isUnion(); }
4899
4900 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004901 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4902 unsigned Quals) {
Richard Smithd951a1d2012-02-18 02:02:13 +00004903 unsigned TQ = MD->getTypeQualifiers();
Richard Smithaf136f82012-07-18 03:51:16 +00004904 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4905 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4906 Quals = 0;
4907 return S.LookupSpecialMember(Class, CSM,
4908 ConstArg || (Quals & Qualifiers::Const),
4909 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smithd951a1d2012-02-18 02:02:13 +00004910 MD->getRefQualifier() == RQ_RValue,
4911 TQ & Qualifiers::Const,
4912 TQ & Qualifiers::Volatile);
4913 }
4914
Richard Smith852265f2012-03-30 20:53:28 +00004915 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004916
Richard Smith852265f2012-03-30 20:53:28 +00004917 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004918 bool shouldDeleteForField(FieldDecl *FD);
4919 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004920
Richard Smithaf136f82012-07-18 03:51:16 +00004921 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4922 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004923 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4924 Sema::SpecialMemberOverloadResult *SMOR,
4925 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004926
4927 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00004928};
4929}
4930
John McCalld4274212012-04-09 20:53:23 +00004931/// Is the given special member inaccessible when used on the given
4932/// sub-object.
4933bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4934 CXXMethodDecl *target) {
4935 /// If we're operating on a base class, the object type is the
4936 /// type of this special member.
4937 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004938 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00004939 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4940 objectTy = S.Context.getTypeDeclType(MD->getParent());
4941 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4942
4943 // If we're operating on a field, the object type is the type of the field.
4944 } else {
4945 objectTy = S.Context.getTypeDeclType(target->getParent());
4946 }
4947
4948 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4949}
4950
Richard Smith852265f2012-03-30 20:53:28 +00004951/// Check whether we should delete a special member due to the implicit
4952/// definition containing a call to a special member of a subobject.
4953bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4954 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4955 bool IsDtorCallInCtor) {
4956 CXXMethodDecl *Decl = SMOR->getMethod();
4957 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4958
4959 int DiagKind = -1;
4960
4961 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4962 DiagKind = !Decl ? 0 : 1;
4963 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4964 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00004965 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00004966 DiagKind = 3;
4967 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4968 !Decl->isTrivial()) {
4969 // A member of a union must have a trivial corresponding special member.
4970 // As a weird special case, a destructor call from a union's constructor
4971 // must be accessible and non-deleted, but need not be trivial. Such a
4972 // destructor is never actually called, but is semantically checked as
4973 // if it were.
4974 DiagKind = 4;
4975 }
4976
4977 if (DiagKind == -1)
4978 return false;
4979
4980 if (Diagnose) {
4981 if (Field) {
4982 S.Diag(Field->getLocation(),
4983 diag::note_deleted_special_member_class_subobject)
4984 << CSM << MD->getParent() << /*IsField*/true
4985 << Field << DiagKind << IsDtorCallInCtor;
4986 } else {
4987 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4988 S.Diag(Base->getLocStart(),
4989 diag::note_deleted_special_member_class_subobject)
4990 << CSM << MD->getParent() << /*IsField*/false
4991 << Base->getType() << DiagKind << IsDtorCallInCtor;
4992 }
4993
4994 if (DiagKind == 1)
4995 S.NoteDeletedFunction(Decl);
4996 // FIXME: Explain inaccessibility if DiagKind == 3.
4997 }
4998
4999 return true;
5000}
5001
Richard Smith921bd202012-02-26 09:11:52 +00005002/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005003/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005004bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005005 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005006 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smithd951a1d2012-02-18 02:02:13 +00005007
5008 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005009 // -- any direct or virtual base class, or non-static data member with no
5010 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005011 // either M has no default constructor or overload resolution as applied
5012 // to M's default constructor results in an ambiguity or in a function
5013 // that is deleted or inaccessible
5014 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5015 // -- a direct or virtual base class B that cannot be copied/moved because
5016 // overload resolution, as applied to B's corresponding special member,
5017 // results in an ambiguity or a function that is deleted or inaccessible
5018 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005019 // C++11 [class.dtor]p5:
5020 // -- any direct or virtual base class [...] has a type with a destructor
5021 // that is deleted or inaccessible
5022 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005023 Field && Field->hasInClassInitializer()) &&
Richard Smithaf136f82012-07-18 03:51:16 +00005024 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005025 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005026
Richard Smith852265f2012-03-30 20:53:28 +00005027 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5028 // -- any direct or virtual base class or non-static data member has a
5029 // type with a destructor that is deleted or inaccessible
5030 if (IsConstructor) {
5031 Sema::SpecialMemberOverloadResult *SMOR =
5032 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5033 false, false, false, false, false);
5034 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5035 return true;
5036 }
5037
Richard Smith921bd202012-02-26 09:11:52 +00005038 return false;
5039}
5040
5041/// Check whether we should delete a special member function due to the class
5042/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005043bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005044 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005045 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005046}
5047
5048/// Check whether we should delete a special member function due to the class
5049/// having a particular non-static data member.
5050bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5051 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5052 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5053
5054 if (CSM == Sema::CXXDefaultConstructor) {
5055 // For a default constructor, all references must be initialized in-class
5056 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005057 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5058 if (Diagnose)
5059 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5060 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005061 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005062 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005063 // C++11 [class.ctor]p5: any non-variant non-static data member of
5064 // const-qualified type (or array thereof) with no
5065 // brace-or-equal-initializer does not have a user-provided default
5066 // constructor.
5067 if (!inUnion() && FieldType.isConstQualified() &&
5068 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005069 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5070 if (Diagnose)
5071 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005072 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005073 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005074 }
5075
5076 if (inUnion() && !FieldType.isConstQualified())
5077 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005078 } else if (CSM == Sema::CXXCopyConstructor) {
5079 // For a copy constructor, data members must not be of rvalue reference
5080 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005081 if (FieldType->isRValueReferenceType()) {
5082 if (Diagnose)
5083 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5084 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005085 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005086 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005087 } else if (IsAssignment) {
5088 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005089 if (FieldType->isReferenceType()) {
5090 if (Diagnose)
5091 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5092 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005093 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005094 }
5095 if (!FieldRecord && FieldType.isConstQualified()) {
5096 // C++11 [class.copy]p23:
5097 // -- a non-static data member of const non-class type (or array thereof)
5098 if (Diagnose)
5099 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005100 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005101 return true;
5102 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005103 }
5104
5105 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005106 // Some additional restrictions exist on the variant members.
5107 if (!inUnion() && FieldRecord->isUnion() &&
5108 FieldRecord->isAnonymousStructOrUnion()) {
5109 bool AllVariantFieldsAreConst = true;
5110
Richard Smith5704fe82012-03-29 19:00:10 +00005111 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00005112 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5113 UE = FieldRecord->field_end();
5114 UI != UE; ++UI) {
5115 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005116
5117 if (!UnionFieldType.isConstQualified())
5118 AllVariantFieldsAreConst = false;
5119
Richard Smith921bd202012-02-26 09:11:52 +00005120 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5121 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00005122 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5123 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005124 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005125 }
5126
5127 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005128 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00005129 FieldRecord->field_begin() != FieldRecord->field_end()) {
5130 if (Diagnose)
5131 S.Diag(FieldRecord->getLocation(),
5132 diag::note_deleted_default_ctor_all_const)
5133 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005134 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005135 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005136
Richard Smith5704fe82012-03-29 19:00:10 +00005137 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005138 // This is technically non-conformant, but sanity demands it.
5139 return false;
5140 }
5141
Richard Smithaf136f82012-07-18 03:51:16 +00005142 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5143 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005144 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005145 }
5146
5147 return false;
5148}
5149
5150/// C++11 [class.ctor] p5:
5151/// A defaulted default constructor for a class X is defined as deleted if
5152/// X is a union and all of its variant members are of const-qualified type.
5153bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005154 // This is a silly definition, because it gives an empty union a deleted
5155 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005156 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5157 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5158 if (Diagnose)
5159 S.Diag(MD->getParent()->getLocation(),
5160 diag::note_deleted_default_ctor_all_const)
5161 << MD->getParent() << /*not anonymous union*/0;
5162 return true;
5163 }
5164 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005165}
5166
5167/// Determine whether a defaulted special member function should be defined as
5168/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5169/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005170bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5171 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005172 if (MD->isInvalidDecl())
5173 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005174 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005175 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005176 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005177 return false;
5178
Richard Smithd951a1d2012-02-18 02:02:13 +00005179 // C++11 [expr.lambda.prim]p19:
5180 // The closure type associated with a lambda-expression has a
5181 // deleted (8.4.3) default constructor and a deleted copy
5182 // assignment operator.
5183 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005184 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5185 if (Diagnose)
5186 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005187 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005188 }
5189
Richard Smith6f1e2c62012-04-02 20:59:25 +00005190 // For an anonymous struct or union, the copy and assignment special members
5191 // will never be used, so skip the check. For an anonymous union declared at
5192 // namespace scope, the constructor and destructor are used.
5193 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5194 RD->isAnonymousStructOrUnion())
5195 return false;
5196
Richard Smith852265f2012-03-30 20:53:28 +00005197 // C++11 [class.copy]p7, p18:
5198 // If the class definition declares a move constructor or move assignment
5199 // operator, an implicitly declared copy constructor or copy assignment
5200 // operator is defined as deleted.
5201 if (MD->isImplicit() &&
5202 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5203 CXXMethodDecl *UserDeclaredMove = 0;
5204
5205 // In Microsoft mode, a user-declared move only causes the deletion of the
5206 // corresponding copy operation, not both copy operations.
5207 if (RD->hasUserDeclaredMoveConstructor() &&
5208 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5209 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005210
5211 // Find any user-declared move constructor.
5212 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5213 E = RD->ctor_end(); I != E; ++I) {
5214 if (I->isMoveConstructor()) {
5215 UserDeclaredMove = *I;
5216 break;
5217 }
5218 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005219 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005220 } else if (RD->hasUserDeclaredMoveAssignment() &&
5221 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5222 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005223
5224 // Find any user-declared move assignment operator.
5225 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5226 E = RD->method_end(); I != E; ++I) {
5227 if (I->isMoveAssignmentOperator()) {
5228 UserDeclaredMove = *I;
5229 break;
5230 }
5231 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005232 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005233 }
5234
5235 if (UserDeclaredMove) {
5236 Diag(UserDeclaredMove->getLocation(),
5237 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005238 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005239 << UserDeclaredMove->isMoveAssignmentOperator();
5240 return true;
5241 }
5242 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005243
Richard Smith6f1e2c62012-04-02 20:59:25 +00005244 // Do access control from the special member function
5245 ContextRAII MethodContext(*this, MD);
5246
Richard Smith921bd202012-02-26 09:11:52 +00005247 // C++11 [class.dtor]p5:
5248 // -- for a virtual destructor, lookup of the non-array deallocation function
5249 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005250 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005251 FunctionDecl *OperatorDelete = 0;
5252 DeclarationName Name =
5253 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5254 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005255 OperatorDelete, false)) {
5256 if (Diagnose)
5257 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005258 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005259 }
Richard Smith921bd202012-02-26 09:11:52 +00005260 }
5261
Richard Smith852265f2012-03-30 20:53:28 +00005262 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005263
Alexis Huntea6f0322011-05-11 22:34:38 +00005264 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005265 BE = RD->bases_end(); BI != BE; ++BI)
5266 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005267 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005268 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005269
Richard Smithd1627032013-07-22 18:06:23 +00005270 // Per DR1611, do not consider virtual bases of constructors of abstract
5271 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005272 if (!RD->isAbstract() || !SMI.IsConstructor) {
5273 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5274 BE = RD->vbases_end();
5275 BI != BE; ++BI)
5276 if (SMI.shouldDeleteForBase(BI))
5277 return true;
5278 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005279
5280 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005281 FE = RD->field_end(); FI != FE; ++FI)
5282 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005283 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005284 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005285
Richard Smithd951a1d2012-02-18 02:02:13 +00005286 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005287 return true;
5288
5289 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005290}
5291
Richard Smith92f241f2012-12-08 02:53:02 +00005292/// Perform lookup for a special member of the specified kind, and determine
5293/// whether it is trivial. If the triviality can be determined without the
5294/// lookup, skip it. This is intended for use when determining whether a
5295/// special member of a containing object is trivial, and thus does not ever
5296/// perform overload resolution for default constructors.
5297///
5298/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5299/// member that was most likely to be intended to be trivial, if any.
5300static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5301 Sema::CXXSpecialMember CSM, unsigned Quals,
5302 CXXMethodDecl **Selected) {
5303 if (Selected)
5304 *Selected = 0;
5305
5306 switch (CSM) {
5307 case Sema::CXXInvalid:
5308 llvm_unreachable("not a special member");
5309
5310 case Sema::CXXDefaultConstructor:
5311 // C++11 [class.ctor]p5:
5312 // A default constructor is trivial if:
5313 // - all the [direct subobjects] have trivial default constructors
5314 //
5315 // Note, no overload resolution is performed in this case.
5316 if (RD->hasTrivialDefaultConstructor())
5317 return true;
5318
5319 if (Selected) {
5320 // If there's a default constructor which could have been trivial, dig it
5321 // out. Otherwise, if there's any user-provided default constructor, point
5322 // to that as an example of why there's not a trivial one.
5323 CXXConstructorDecl *DefCtor = 0;
5324 if (RD->needsImplicitDefaultConstructor())
5325 S.DeclareImplicitDefaultConstructor(RD);
5326 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5327 CE = RD->ctor_end(); CI != CE; ++CI) {
5328 if (!CI->isDefaultConstructor())
5329 continue;
5330 DefCtor = *CI;
5331 if (!DefCtor->isUserProvided())
5332 break;
5333 }
5334
5335 *Selected = DefCtor;
5336 }
5337
5338 return false;
5339
5340 case Sema::CXXDestructor:
5341 // C++11 [class.dtor]p5:
5342 // A destructor is trivial if:
5343 // - all the direct [subobjects] have trivial destructors
5344 if (RD->hasTrivialDestructor())
5345 return true;
5346
5347 if (Selected) {
5348 if (RD->needsImplicitDestructor())
5349 S.DeclareImplicitDestructor(RD);
5350 *Selected = RD->getDestructor();
5351 }
5352
5353 return false;
5354
5355 case Sema::CXXCopyConstructor:
5356 // C++11 [class.copy]p12:
5357 // A copy constructor is trivial if:
5358 // - the constructor selected to copy each direct [subobject] is trivial
5359 if (RD->hasTrivialCopyConstructor()) {
5360 if (Quals == Qualifiers::Const)
5361 // We must either select the trivial copy constructor or reach an
5362 // ambiguity; no need to actually perform overload resolution.
5363 return true;
5364 } else if (!Selected) {
5365 return false;
5366 }
5367 // In C++98, we are not supposed to perform overload resolution here, but we
5368 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5369 // cases like B as having a non-trivial copy constructor:
5370 // struct A { template<typename T> A(T&); };
5371 // struct B { mutable A a; };
5372 goto NeedOverloadResolution;
5373
5374 case Sema::CXXCopyAssignment:
5375 // C++11 [class.copy]p25:
5376 // A copy assignment operator is trivial if:
5377 // - the assignment operator selected to copy each direct [subobject] is
5378 // trivial
5379 if (RD->hasTrivialCopyAssignment()) {
5380 if (Quals == Qualifiers::Const)
5381 return true;
5382 } else if (!Selected) {
5383 return false;
5384 }
5385 // In C++98, we are not supposed to perform overload resolution here, but we
5386 // treat that as a language defect.
5387 goto NeedOverloadResolution;
5388
5389 case Sema::CXXMoveConstructor:
5390 case Sema::CXXMoveAssignment:
5391 NeedOverloadResolution:
5392 Sema::SpecialMemberOverloadResult *SMOR =
5393 S.LookupSpecialMember(RD, CSM,
5394 Quals & Qualifiers::Const,
5395 Quals & Qualifiers::Volatile,
5396 /*RValueThis*/false, /*ConstThis*/false,
5397 /*VolatileThis*/false);
5398
5399 // The standard doesn't describe how to behave if the lookup is ambiguous.
5400 // We treat it as not making the member non-trivial, just like the standard
5401 // mandates for the default constructor. This should rarely matter, because
5402 // the member will also be deleted.
5403 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5404 return true;
5405
5406 if (!SMOR->getMethod()) {
5407 assert(SMOR->getKind() ==
5408 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5409 return false;
5410 }
5411
5412 // We deliberately don't check if we found a deleted special member. We're
5413 // not supposed to!
5414 if (Selected)
5415 *Selected = SMOR->getMethod();
5416 return SMOR->getMethod()->isTrivial();
5417 }
5418
5419 llvm_unreachable("unknown special method kind");
5420}
5421
Benjamin Kramer3e350262013-02-15 12:30:38 +00005422static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005423 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5424 CI != CE; ++CI)
5425 if (!CI->isImplicit())
5426 return *CI;
5427
5428 // Look for constructor templates.
5429 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5430 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5431 if (CXXConstructorDecl *CD =
5432 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5433 return CD;
5434 }
5435
5436 return 0;
5437}
5438
5439/// The kind of subobject we are checking for triviality. The values of this
5440/// enumeration are used in diagnostics.
5441enum TrivialSubobjectKind {
5442 /// The subobject is a base class.
5443 TSK_BaseClass,
5444 /// The subobject is a non-static data member.
5445 TSK_Field,
5446 /// The object is actually the complete object.
5447 TSK_CompleteObject
5448};
5449
5450/// Check whether the special member selected for a given type would be trivial.
5451static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5452 QualType SubType,
5453 Sema::CXXSpecialMember CSM,
5454 TrivialSubobjectKind Kind,
5455 bool Diagnose) {
5456 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5457 if (!SubRD)
5458 return true;
5459
5460 CXXMethodDecl *Selected;
5461 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5462 Diagnose ? &Selected : 0))
5463 return true;
5464
5465 if (Diagnose) {
5466 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5467 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5468 << Kind << SubType.getUnqualifiedType();
5469 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5470 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5471 } else if (!Selected)
5472 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5473 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5474 else if (Selected->isUserProvided()) {
5475 if (Kind == TSK_CompleteObject)
5476 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5477 << Kind << SubType.getUnqualifiedType() << CSM;
5478 else {
5479 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5480 << Kind << SubType.getUnqualifiedType() << CSM;
5481 S.Diag(Selected->getLocation(), diag::note_declared_at);
5482 }
5483 } else {
5484 if (Kind != TSK_CompleteObject)
5485 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5486 << Kind << SubType.getUnqualifiedType() << CSM;
5487
5488 // Explain why the defaulted or deleted special member isn't trivial.
5489 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5490 }
5491 }
5492
5493 return false;
5494}
5495
5496/// Check whether the members of a class type allow a special member to be
5497/// trivial.
5498static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5499 Sema::CXXSpecialMember CSM,
5500 bool ConstArg, bool Diagnose) {
5501 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5502 FE = RD->field_end(); FI != FE; ++FI) {
5503 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5504 continue;
5505
5506 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5507
5508 // Pretend anonymous struct or union members are members of this class.
5509 if (FI->isAnonymousStructOrUnion()) {
5510 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5511 CSM, ConstArg, Diagnose))
5512 return false;
5513 continue;
5514 }
5515
5516 // C++11 [class.ctor]p5:
5517 // A default constructor is trivial if [...]
5518 // -- no non-static data member of its class has a
5519 // brace-or-equal-initializer
5520 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5521 if (Diagnose)
5522 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5523 return false;
5524 }
5525
5526 // Objective C ARC 4.3.5:
5527 // [...] nontrivally ownership-qualified types are [...] not trivially
5528 // default constructible, copy constructible, move constructible, copy
5529 // assignable, move assignable, or destructible [...]
5530 if (S.getLangOpts().ObjCAutoRefCount &&
5531 FieldType.hasNonTrivialObjCLifetime()) {
5532 if (Diagnose)
5533 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5534 << RD << FieldType.getObjCLifetime();
5535 return false;
5536 }
5537
5538 if (ConstArg && !FI->isMutable())
5539 FieldType.addConst();
5540 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5541 TSK_Field, Diagnose))
5542 return false;
5543 }
5544
5545 return true;
5546}
5547
5548/// Diagnose why the specified class does not have a trivial special member of
5549/// the given kind.
5550void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5551 QualType Ty = Context.getRecordType(RD);
5552 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5553 Ty.addConst();
5554
5555 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5556 TSK_CompleteObject, /*Diagnose*/true);
5557}
5558
5559/// Determine whether a defaulted or deleted special member function is trivial,
5560/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5561/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5562bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5563 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005564 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5565
5566 CXXRecordDecl *RD = MD->getParent();
5567
5568 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005569
5570 // C++11 [class.copy]p12, p25:
5571 // A [special member] is trivial if its declared parameter type is the same
5572 // as if it had been implicitly declared [...]
5573 switch (CSM) {
5574 case CXXDefaultConstructor:
5575 case CXXDestructor:
5576 // Trivial default constructors and destructors cannot have parameters.
5577 break;
5578
5579 case CXXCopyConstructor:
5580 case CXXCopyAssignment: {
5581 // Trivial copy operations always have const, non-volatile parameter types.
5582 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005583 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005584 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5585 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5586 if (Diagnose)
5587 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5588 << Param0->getSourceRange() << Param0->getType()
5589 << Context.getLValueReferenceType(
5590 Context.getRecordType(RD).withConst());
5591 return false;
5592 }
5593 break;
5594 }
5595
5596 case CXXMoveConstructor:
5597 case CXXMoveAssignment: {
5598 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005599 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005600 const RValueReferenceType *RT =
5601 Param0->getType()->getAs<RValueReferenceType>();
5602 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5603 if (Diagnose)
5604 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5605 << Param0->getSourceRange() << Param0->getType()
5606 << Context.getRValueReferenceType(Context.getRecordType(RD));
5607 return false;
5608 }
5609 break;
5610 }
5611
5612 case CXXInvalid:
5613 llvm_unreachable("not a special member");
5614 }
5615
5616 // FIXME: We require that the parameter-declaration-clause is equivalent to
5617 // that of an implicit declaration, not just that the declared parameter type
5618 // matches, in order to prevent absuridities like a function simultaneously
5619 // being a trivial copy constructor and a non-trivial default constructor.
5620 // This issue has not yet been assigned a core issue number.
5621 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5622 if (Diagnose)
5623 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5624 diag::note_nontrivial_default_arg)
5625 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5626 return false;
5627 }
5628 if (MD->isVariadic()) {
5629 if (Diagnose)
5630 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5631 return false;
5632 }
5633
5634 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5635 // A copy/move [constructor or assignment operator] is trivial if
5636 // -- the [member] selected to copy/move each direct base class subobject
5637 // is trivial
5638 //
5639 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5640 // A [default constructor or destructor] is trivial if
5641 // -- all the direct base classes have trivial [default constructors or
5642 // destructors]
5643 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5644 BE = RD->bases_end(); BI != BE; ++BI)
5645 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5646 ConstArg ? BI->getType().withConst()
5647 : BI->getType(),
5648 CSM, TSK_BaseClass, Diagnose))
5649 return false;
5650
5651 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5652 // A copy/move [constructor or assignment operator] for a class X is
5653 // trivial if
5654 // -- for each non-static data member of X that is of class type (or array
5655 // thereof), the constructor selected to copy/move that member is
5656 // trivial
5657 //
5658 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5659 // A [default constructor or destructor] is trivial if
5660 // -- for all of the non-static data members of its class that are of class
5661 // type (or array thereof), each such class has a trivial [default
5662 // constructor or destructor]
5663 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5664 return false;
5665
5666 // C++11 [class.dtor]p5:
5667 // A destructor is trivial if [...]
5668 // -- the destructor is not virtual
5669 if (CSM == CXXDestructor && MD->isVirtual()) {
5670 if (Diagnose)
5671 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5672 return false;
5673 }
5674
5675 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5676 // A [special member] for class X is trivial if [...]
5677 // -- class X has no virtual functions and no virtual base classes
5678 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5679 if (!Diagnose)
5680 return false;
5681
5682 if (RD->getNumVBases()) {
5683 // Check for virtual bases. We already know that the corresponding
5684 // member in all bases is trivial, so vbases must all be direct.
5685 CXXBaseSpecifier &BS = *RD->vbases_begin();
5686 assert(BS.isVirtual());
5687 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5688 return false;
5689 }
5690
5691 // Must have a virtual method.
5692 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5693 ME = RD->method_end(); MI != ME; ++MI) {
5694 if (MI->isVirtual()) {
5695 SourceLocation MLoc = MI->getLocStart();
5696 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5697 return false;
5698 }
5699 }
5700
5701 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5702 }
5703
5704 // Looks like it's trivial!
5705 return true;
5706}
5707
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005708/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005709namespace {
5710 struct FindHiddenVirtualMethodData {
5711 Sema *S;
5712 CXXMethodDecl *Method;
5713 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005714 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005715 };
5716}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005717
David Blaikie282c92a2012-10-19 00:53:08 +00005718/// \brief Check whether any most overriden method from MD in Methods
5719static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5720 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5721 if (MD->size_overridden_methods() == 0)
5722 return Methods.count(MD->getCanonicalDecl());
5723 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5724 E = MD->end_overridden_methods();
5725 I != E; ++I)
5726 if (CheckMostOverridenMethods(*I, Methods))
5727 return true;
5728 return false;
5729}
5730
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005731/// \brief Member lookup function that determines whether a given C++
5732/// method overloads virtual methods in a base class without overriding any,
5733/// to be used with CXXRecordDecl::lookupInBases().
5734static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5735 CXXBasePath &Path,
5736 void *UserData) {
5737 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5738
5739 FindHiddenVirtualMethodData &Data
5740 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5741
5742 DeclarationName Name = Data.Method->getDeclName();
5743 assert(Name.getNameKind() == DeclarationName::Identifier);
5744
5745 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005746 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005747 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005748 !Path.Decls.empty();
5749 Path.Decls = Path.Decls.slice(1)) {
5750 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005751 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005752 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005753 foundSameNameMethod = true;
5754 // Interested only in hidden virtual methods.
5755 if (!MD->isVirtual())
5756 continue;
5757 // If the method we are checking overrides a method from its base
5758 // don't warn about the other overloaded methods.
5759 if (!Data.S->IsOverload(Data.Method, MD, false))
5760 return true;
5761 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005762 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005763 overloadedMethods.push_back(MD);
5764 }
5765 }
5766
5767 if (foundSameNameMethod)
5768 Data.OverloadedMethods.append(overloadedMethods.begin(),
5769 overloadedMethods.end());
5770 return foundSameNameMethod;
5771}
5772
David Blaikie282c92a2012-10-19 00:53:08 +00005773/// \brief Add the most overriden methods from MD to Methods
5774static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5775 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5776 if (MD->size_overridden_methods() == 0)
5777 Methods.insert(MD->getCanonicalDecl());
5778 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5779 E = MD->end_overridden_methods();
5780 I != E; ++I)
5781 AddMostOverridenMethods(*I, Methods);
5782}
5783
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005784/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005785/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005786void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5787 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005788 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005789 return;
5790
5791 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5792 /*bool RecordPaths=*/false,
5793 /*bool DetectVirtual=*/false);
5794 FindHiddenVirtualMethodData Data;
5795 Data.Method = MD;
5796 Data.S = this;
5797
5798 // Keep the base methods that were overriden or introduced in the subclass
5799 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005800 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005801 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5802 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5803 NamedDecl *ND = *I;
5804 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005805 ND = shad->getTargetDecl();
5806 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5807 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005808 }
5809
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005810 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5811 OverloadedMethods = Data.OverloadedMethods;
5812}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005813
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005814void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5815 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5816 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5817 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5818 PartialDiagnostic PD = PDiag(
5819 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5820 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5821 Diag(overloadedMD->getLocation(), PD);
5822 }
5823}
5824
5825/// \brief Diagnose methods which overload virtual methods in a base class
5826/// without overriding any.
5827void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5828 if (MD->isInvalidDecl())
5829 return;
5830
5831 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5832 MD->getLocation()) == DiagnosticsEngine::Ignored)
5833 return;
5834
5835 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5836 FindHiddenVirtualMethods(MD, OverloadedMethods);
5837 if (!OverloadedMethods.empty()) {
5838 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5839 << MD << (OverloadedMethods.size() > 1);
5840
5841 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005842 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005843}
5844
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005845void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005846 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005847 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005848 SourceLocation RBrac,
5849 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005850 if (!TagDecl)
5851 return;
Mike Stump11289f42009-09-09 15:08:12 +00005852
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005853 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005854
Rafael Espindola06e1b132012-07-12 04:32:30 +00005855 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5856 if (l->getKind() != AttributeList::AT_Visibility)
5857 continue;
5858 l->setInvalid();
5859 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5860 l->getName();
5861 }
5862
David Blaikie751c5582011-09-22 02:58:26 +00005863 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005864 // strict aliasing violation!
5865 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005866 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005867
Douglas Gregor0be31a22010-07-02 17:43:08 +00005868 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005869 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005870}
5871
Douglas Gregor05379422008-11-03 17:51:48 +00005872/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5873/// special functions, such as the default constructor, copy
5874/// constructor, or destructor, to the given C++ class (C++
5875/// [special]p1). This routine can only be executed just before the
5876/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005877void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005878 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005879 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005880
Richard Smith6b02d462012-12-08 08:32:28 +00005881 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005882 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005883
Richard Smith6b02d462012-12-08 08:32:28 +00005884 // If the properties or semantics of the copy constructor couldn't be
5885 // determined while the class was being declared, force a declaration
5886 // of it now.
5887 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5888 DeclareImplicitCopyConstructor(ClassDecl);
5889 }
5890
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005891 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005892 ++ASTContext::NumImplicitMoveConstructors;
5893
Richard Smith6b02d462012-12-08 08:32:28 +00005894 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5895 DeclareImplicitMoveConstructor(ClassDecl);
5896 }
5897
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005898 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5899 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005900
5901 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005902 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005903 // it shows up in the right place in the vtable and that we diagnose
5904 // problems with the implicit exception specification.
5905 if (ClassDecl->isDynamicClass() ||
5906 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005907 DeclareImplicitCopyAssignment(ClassDecl);
5908 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005909
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005910 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005911 ++ASTContext::NumImplicitMoveAssignmentOperators;
5912
5913 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005914 if (ClassDecl->isDynamicClass() ||
5915 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005916 DeclareImplicitMoveAssignment(ClassDecl);
5917 }
5918
Douglas Gregor7454c562010-07-02 20:37:36 +00005919 if (!ClassDecl->hasUserDeclaredDestructor()) {
5920 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005921
5922 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005923 // have to declare the destructor immediately. This ensures that, e.g., it
5924 // shows up in the right place in the vtable and that we diagnose problems
5925 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005926 if (ClassDecl->isDynamicClass() ||
5927 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005928 DeclareImplicitDestructor(ClassDecl);
5929 }
Douglas Gregor05379422008-11-03 17:51:48 +00005930}
5931
Francois Pichet1c229c02011-04-22 22:18:13 +00005932void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5933 if (!D)
5934 return;
5935
5936 int NumParamList = D->getNumTemplateParameterLists();
5937 for (int i = 0; i < NumParamList; i++) {
5938 TemplateParameterList* Params = D->getTemplateParameterList(i);
5939 for (TemplateParameterList::iterator Param = Params->begin(),
5940 ParamEnd = Params->end();
5941 Param != ParamEnd; ++Param) {
5942 NamedDecl *Named = cast<NamedDecl>(*Param);
5943 if (Named->getDeclName()) {
5944 S->AddDecl(Named);
5945 IdResolver.AddDecl(Named);
5946 }
5947 }
5948 }
5949}
5950
John McCall48871652010-08-21 09:40:31 +00005951void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005952 if (!D)
5953 return;
5954
5955 TemplateParameterList *Params = 0;
5956 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5957 Params = Template->getTemplateParameters();
5958 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5959 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5960 Params = PartialSpec->getTemplateParameters();
5961 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005962 return;
5963
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005964 for (TemplateParameterList::iterator Param = Params->begin(),
5965 ParamEnd = Params->end();
5966 Param != ParamEnd; ++Param) {
5967 NamedDecl *Named = cast<NamedDecl>(*Param);
5968 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005969 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005970 IdResolver.AddDecl(Named);
5971 }
5972 }
5973}
5974
John McCall48871652010-08-21 09:40:31 +00005975void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005976 if (!RecordD) return;
5977 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005978 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005979 PushDeclContext(S, Record);
5980}
5981
John McCall48871652010-08-21 09:40:31 +00005982void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005983 if (!RecordD) return;
5984 PopDeclContext();
5985}
5986
Douglas Gregor4d87df52008-12-16 21:30:33 +00005987/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5988/// parsing a top-level (non-nested) C++ class, and we are now
5989/// parsing those parts of the given Method declaration that could
5990/// not be parsed earlier (C++ [class.mem]p2), such as default
5991/// arguments. This action should enter the scope of the given
5992/// Method declaration as if we had just parsed the qualified method
5993/// name. However, it should not bring the parameters into scope;
5994/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005995void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005996}
5997
5998/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5999/// C++ method declaration. We're (re-)introducing the given
6000/// function parameter into scope for use in parsing later parts of
6001/// the method declaration. For example, we could see an
6002/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006003void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006004 if (!ParamD)
6005 return;
Mike Stump11289f42009-09-09 15:08:12 +00006006
John McCall48871652010-08-21 09:40:31 +00006007 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006008
6009 // If this parameter has an unparsed default argument, clear it out
6010 // to make way for the parsed default argument.
6011 if (Param->hasUnparsedDefaultArg())
6012 Param->setDefaultArg(0);
6013
John McCall48871652010-08-21 09:40:31 +00006014 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006015 if (Param->getDeclName())
6016 IdResolver.AddDecl(Param);
6017}
6018
6019/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6020/// processing the delayed method declaration for Method. The method
6021/// declaration is now considered finished. There may be a separate
6022/// ActOnStartOfFunctionDef action later (not necessarily
6023/// immediately!) for this method, if it was also defined inside the
6024/// class body.
John McCall48871652010-08-21 09:40:31 +00006025void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006026 if (!MethodD)
6027 return;
Mike Stump11289f42009-09-09 15:08:12 +00006028
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006029 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006030
John McCall48871652010-08-21 09:40:31 +00006031 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006032
6033 // Now that we have our default arguments, check the constructor
6034 // again. It could produce additional diagnostics or affect whether
6035 // the class has implicitly-declared destructors, among other
6036 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006037 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6038 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006039
6040 // Check the default arguments, which we may have added.
6041 if (!Method->isInvalidDecl())
6042 CheckCXXDefaultArguments(Method);
6043}
6044
Douglas Gregor831c93f2008-11-05 20:51:48 +00006045/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006046/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006047/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006048/// emit diagnostics and set the invalid bit to true. In any case, the type
6049/// will be updated to reflect a well-formed type for the constructor and
6050/// returned.
6051QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006052 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006053 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006054
6055 // C++ [class.ctor]p3:
6056 // A constructor shall not be virtual (10.3) or static (9.4). A
6057 // constructor can be invoked for a const, volatile or const
6058 // volatile object. A constructor shall not be declared const,
6059 // volatile, or const volatile (9.3.2).
6060 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006061 if (!D.isInvalidType())
6062 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6063 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6064 << SourceRange(D.getIdentifierLoc());
6065 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006066 }
John McCall8e7d6562010-08-26 03:08:43 +00006067 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006068 if (!D.isInvalidType())
6069 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6070 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6071 << SourceRange(D.getIdentifierLoc());
6072 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006073 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006074 }
Mike Stump11289f42009-09-09 15:08:12 +00006075
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006076 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006077 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006078 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6080 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006081 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6083 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006084 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006085 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6086 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006087 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006088 }
Mike Stump11289f42009-09-09 15:08:12 +00006089
Douglas Gregordb9d6642011-01-26 05:01:58 +00006090 // C++0x [class.ctor]p4:
6091 // A constructor shall not be declared with a ref-qualifier.
6092 if (FTI.hasRefQualifier()) {
6093 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6094 << FTI.RefQualifierIsLValueRef
6095 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6096 D.setInvalidType();
6097 }
6098
Douglas Gregor831c93f2008-11-05 20:51:48 +00006099 // Rebuild the function type "R" without any type qualifiers (in
6100 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006101 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006102 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006103 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6104 return R;
6105
6106 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6107 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006108 EPI.RefQualifier = RQ_None;
6109
Richard Smithc2bc61b2013-03-18 21:12:30 +00006110 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006111}
6112
Douglas Gregor4d87df52008-12-16 21:30:33 +00006113/// CheckConstructor - Checks a fully-formed constructor for
6114/// well-formedness, issuing any diagnostics required. Returns true if
6115/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006116void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006117 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006118 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6119 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006120 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006121
6122 // C++ [class.copy]p3:
6123 // A declaration of a constructor for a class X is ill-formed if
6124 // its first parameter is of type (optionally cv-qualified) X and
6125 // either there are no other parameters or else all other
6126 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006127 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006128 ((Constructor->getNumParams() == 1) ||
6129 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006130 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6131 Constructor->getTemplateSpecializationKind()
6132 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006133 QualType ParamType = Constructor->getParamDecl(0)->getType();
6134 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6135 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006136 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006137 const char *ConstRef
6138 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6139 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006140 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006141 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006142
6143 // FIXME: Rather that making the constructor invalid, we should endeavor
6144 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006145 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006146 }
6147 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006148}
6149
John McCalldeb646e2010-08-04 01:04:25 +00006150/// CheckDestructor - Checks a fully-formed destructor definition for
6151/// well-formedness, issuing any diagnostics required. Returns true
6152/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006153bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006154 CXXRecordDecl *RD = Destructor->getParent();
6155
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006156 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006157 SourceLocation Loc;
6158
6159 if (!Destructor->isImplicit())
6160 Loc = Destructor->getLocation();
6161 else
6162 Loc = RD->getLocation();
6163
6164 // If we have a virtual destructor, look up the deallocation function
6165 FunctionDecl *OperatorDelete = 0;
6166 DeclarationName Name =
6167 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006168 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006169 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00006170
Eli Friedmanfa0df832012-02-02 03:46:19 +00006171 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006172
6173 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006174 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006175
6176 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006177}
6178
Mike Stump11289f42009-09-09 15:08:12 +00006179static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006180FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6181 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6182 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006183 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006184}
6185
Douglas Gregor831c93f2008-11-05 20:51:48 +00006186/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6187/// the well-formednes of the destructor declarator @p D with type @p
6188/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006189/// emit diagnostics and set the declarator to invalid. Even if this happens,
6190/// will be updated to reflect a well-formed type for the destructor and
6191/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006192QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006193 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006194 // C++ [class.dtor]p1:
6195 // [...] A typedef-name that names a class is a class-name
6196 // (7.1.3); however, a typedef-name that names a class shall not
6197 // be used as the identifier in the declarator for a destructor
6198 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006199 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006200 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006201 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006202 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006203 else if (const TemplateSpecializationType *TST =
6204 DeclaratorType->getAs<TemplateSpecializationType>())
6205 if (TST->isTypeAlias())
6206 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6207 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006208
6209 // C++ [class.dtor]p2:
6210 // A destructor is used to destroy objects of its class type. A
6211 // destructor takes no parameters, and no return type can be
6212 // specified for it (not even void). The address of a destructor
6213 // shall not be taken. A destructor shall not be static. A
6214 // destructor can be invoked for a const, volatile or const
6215 // volatile object. A destructor shall not be declared const,
6216 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006217 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006218 if (!D.isInvalidType())
6219 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6220 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006221 << SourceRange(D.getIdentifierLoc())
6222 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6223
John McCall8e7d6562010-08-26 03:08:43 +00006224 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006225 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006226 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006227 // Destructors don't have return types, but the parser will
6228 // happily parse something like:
6229 //
6230 // class X {
6231 // float ~X();
6232 // };
6233 //
6234 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006235 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6236 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6237 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006238 }
Mike Stump11289f42009-09-09 15:08:12 +00006239
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006240 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006241 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006242 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006243 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6244 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006245 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006246 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6247 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006248 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006249 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6250 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006251 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006252 }
6253
Douglas Gregordb9d6642011-01-26 05:01:58 +00006254 // C++0x [class.dtor]p2:
6255 // A destructor shall not be declared with a ref-qualifier.
6256 if (FTI.hasRefQualifier()) {
6257 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6258 << FTI.RefQualifierIsLValueRef
6259 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6260 D.setInvalidType();
6261 }
6262
Douglas Gregor831c93f2008-11-05 20:51:48 +00006263 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00006264 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006265 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6266
6267 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00006268 FTI.freeArgs();
6269 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006270 }
6271
Mike Stump11289f42009-09-09 15:08:12 +00006272 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006273 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006274 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006275 D.setInvalidType();
6276 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006277
6278 // Rebuild the function type "R" without any type qualifiers or
6279 // parameters (in case any of the errors above fired) and with
6280 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006281 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006282 if (!D.isInvalidType())
6283 return R;
6284
Douglas Gregor95755162010-07-01 05:10:53 +00006285 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006286 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6287 EPI.Variadic = false;
6288 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006289 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006290 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006291}
6292
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006293/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6294/// well-formednes of the conversion function declarator @p D with
6295/// type @p R. If there are any errors in the declarator, this routine
6296/// will emit diagnostics and return true. Otherwise, it will return
6297/// false. Either way, the type @p R will be updated to reflect a
6298/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006299void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006300 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006301 // C++ [class.conv.fct]p1:
6302 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006303 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006304 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006305 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006306 if (!D.isInvalidType())
6307 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006308 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6309 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006310 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006311 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006312 }
John McCall212fa2e2010-04-13 00:04:31 +00006313
6314 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6315
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006316 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006317 // Conversion functions don't have return types, but the parser will
6318 // happily parse something like:
6319 //
6320 // class X {
6321 // float operator bool();
6322 // };
6323 //
6324 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006325 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6326 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6327 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006328 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006329 }
6330
John McCall212fa2e2010-04-13 00:04:31 +00006331 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6332
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006333 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00006334 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006335 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6336
6337 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006338 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006339 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006340 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006341 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006342 D.setInvalidType();
6343 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006344
John McCall212fa2e2010-04-13 00:04:31 +00006345 // Diagnose "&operator bool()" and other such nonsense. This
6346 // is actually a gcc extension which we don't support.
6347 if (Proto->getResultType() != ConvType) {
6348 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6349 << Proto->getResultType();
6350 D.setInvalidType();
6351 ConvType = Proto->getResultType();
6352 }
6353
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006354 // C++ [class.conv.fct]p4:
6355 // The conversion-type-id shall not represent a function type nor
6356 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006357 if (ConvType->isArrayType()) {
6358 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6359 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006360 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006361 } else if (ConvType->isFunctionType()) {
6362 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6363 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006364 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006365 }
6366
6367 // Rebuild the function type "R" without any parameters (in case any
6368 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006369 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006370 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006371 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006372
Douglas Gregor5fb53972009-01-14 15:45:31 +00006373 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006374 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006375 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006376 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006377 diag::warn_cxx98_compat_explicit_conversion_functions :
6378 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006379 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006380}
6381
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006382/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6383/// the declaration of the given C++ conversion function. This routine
6384/// is responsible for recording the conversion function in the C++
6385/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006386Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006387 assert(Conversion && "Expected to receive a conversion function declaration");
6388
Douglas Gregor4287b372008-12-12 08:25:50 +00006389 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006390
6391 // Make sure we aren't redeclaring the conversion function.
6392 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006393
6394 // C++ [class.conv.fct]p1:
6395 // [...] A conversion function is never used to convert a
6396 // (possibly cv-qualified) object to the (possibly cv-qualified)
6397 // same object type (or a reference to it), to a (possibly
6398 // cv-qualified) base class of that type (or a reference to it),
6399 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006400 // FIXME: Suppress this warning if the conversion function ends up being a
6401 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006402 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006403 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006404 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006405 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006406 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6407 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006408 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006409 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006410 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6411 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006412 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006413 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006414 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006415 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006416 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006417 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006418 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006419 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006420 }
6421
Douglas Gregor457104e2010-09-29 04:25:11 +00006422 if (FunctionTemplateDecl *ConversionTemplate
6423 = Conversion->getDescribedFunctionTemplate())
6424 return ConversionTemplate;
6425
John McCall48871652010-08-21 09:40:31 +00006426 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006427}
6428
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006429//===----------------------------------------------------------------------===//
6430// Namespace Handling
6431//===----------------------------------------------------------------------===//
6432
Richard Smith45bb8852012-10-04 22:13:39 +00006433/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6434/// reopened.
6435static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6436 SourceLocation Loc,
6437 IdentifierInfo *II, bool *IsInline,
6438 NamespaceDecl *PrevNS) {
6439 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006440
Richard Smithf501cc32012-10-05 01:46:25 +00006441 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6442 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6443 // inline namespaces, with the intention of bringing names into namespace std.
6444 //
6445 // We support this just well enough to get that case working; this is not
6446 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006447 if (*IsInline && II && II->getName().startswith("__atomic") &&
6448 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006449 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006450 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6451 NS = NS->getPreviousDecl())
6452 NS->setInline(*IsInline);
6453 // Patch up the lookup table for the containing namespace. This isn't really
6454 // correct, but it's good enough for this particular case.
6455 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6456 E = PrevNS->decls_end(); I != E; ++I)
6457 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6458 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6459 return;
6460 }
6461
6462 if (PrevNS->isInline())
6463 // The user probably just forgot the 'inline', so suggest that it
6464 // be added back.
6465 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6466 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6467 else
6468 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6469 << IsInline;
6470
6471 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6472 *IsInline = PrevNS->isInline();
6473}
John McCallb1be5232010-08-26 09:15:37 +00006474
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006475/// ActOnStartNamespaceDef - This is called at the start of a namespace
6476/// definition.
John McCall48871652010-08-21 09:40:31 +00006477Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006478 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006479 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006480 SourceLocation IdentLoc,
6481 IdentifierInfo *II,
6482 SourceLocation LBrace,
6483 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006484 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6485 // For anonymous namespace, take the location of the left brace.
6486 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006487 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006488 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006489 bool IsStd = false;
6490 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006491 Scope *DeclRegionScope = NamespcScope->getParent();
6492
Douglas Gregore57e7522012-01-07 09:11:48 +00006493 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006494 if (II) {
6495 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006496 // The identifier in an original-namespace-definition shall not
6497 // have been previously defined in the declarative region in
6498 // which the original-namespace-definition appears. The
6499 // identifier in an original-namespace-definition is the name of
6500 // the namespace. Subsequently in that declarative region, it is
6501 // treated as an original-namespace-name.
6502 //
6503 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006504 // look through using directives, just look for any ordinary names.
6505
6506 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006507 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6508 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006509 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006510 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6511 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6512 ++I) {
6513 if ((*I)->getIdentifierNamespace() & IDNS) {
6514 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006515 break;
6516 }
6517 }
6518
Douglas Gregore57e7522012-01-07 09:11:48 +00006519 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6520
6521 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006522 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006523 if (IsInline != PrevNS->isInline())
6524 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6525 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006526 } else if (PrevDecl) {
6527 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006528 Diag(Loc, diag::err_redefinition_different_kind)
6529 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006530 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006531 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006532 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006533 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006534 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006535 // This is the first "real" definition of the namespace "std", so update
6536 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006537 PrevNS = getStdNamespace();
6538 IsStd = true;
6539 AddToKnown = !IsInline;
6540 } else {
6541 // We've seen this namespace for the first time.
6542 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006543 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006544 } else {
John McCall4fa53422009-10-01 00:25:31 +00006545 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006546
6547 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006548 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006549 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006550 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006551 } else {
6552 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006553 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006554 }
6555
Richard Smith45bb8852012-10-04 22:13:39 +00006556 if (PrevNS && IsInline != PrevNS->isInline())
6557 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6558 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006559 }
6560
6561 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6562 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006563 if (IsInvalid)
6564 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006565
6566 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006567
Douglas Gregore57e7522012-01-07 09:11:48 +00006568 // FIXME: Should we be merging attributes?
6569 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006570 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006571
6572 if (IsStd)
6573 StdNamespace = Namespc;
6574 if (AddToKnown)
6575 KnownNamespaces[Namespc] = false;
6576
6577 if (II) {
6578 PushOnScopeChains(Namespc, DeclRegionScope);
6579 } else {
6580 // Link the anonymous namespace into its parent.
6581 DeclContext *Parent = CurContext->getRedeclContext();
6582 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6583 TU->setAnonymousNamespace(Namespc);
6584 } else {
6585 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006586 }
John McCall4fa53422009-10-01 00:25:31 +00006587
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006588 CurContext->addDecl(Namespc);
6589
John McCall4fa53422009-10-01 00:25:31 +00006590 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6591 // behaves as if it were replaced by
6592 // namespace unique { /* empty body */ }
6593 // using namespace unique;
6594 // namespace unique { namespace-body }
6595 // where all occurrences of 'unique' in a translation unit are
6596 // replaced by the same identifier and this identifier differs
6597 // from all other identifiers in the entire program.
6598
6599 // We just create the namespace with an empty name and then add an
6600 // implicit using declaration, just like the standard suggests.
6601 //
6602 // CodeGen enforces the "universally unique" aspect by giving all
6603 // declarations semantically contained within an anonymous
6604 // namespace internal linkage.
6605
Douglas Gregore57e7522012-01-07 09:11:48 +00006606 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006607 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006608 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006609 /* 'using' */ LBrace,
6610 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006611 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006612 /* identifier */ SourceLocation(),
6613 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006614 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006615 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006616 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006617 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006618 }
6619
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006620 ActOnDocumentableDecl(Namespc);
6621
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006622 // Although we could have an invalid decl (i.e. the namespace name is a
6623 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006624 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6625 // for the namespace has the declarations that showed up in that particular
6626 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006627 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006628 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006629}
6630
Sebastian Redla6602e92009-11-23 15:34:23 +00006631/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6632/// is a namespace alias, returns the namespace it points to.
6633static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6634 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6635 return AD->getNamespace();
6636 return dyn_cast_or_null<NamespaceDecl>(D);
6637}
6638
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006639/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6640/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006641void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006642 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6643 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006644 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006645 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006646 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006647 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006648}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006649
John McCall28a0cf72010-08-25 07:42:41 +00006650CXXRecordDecl *Sema::getStdBadAlloc() const {
6651 return cast_or_null<CXXRecordDecl>(
6652 StdBadAlloc.get(Context.getExternalSource()));
6653}
6654
6655NamespaceDecl *Sema::getStdNamespace() const {
6656 return cast_or_null<NamespaceDecl>(
6657 StdNamespace.get(Context.getExternalSource()));
6658}
6659
Douglas Gregorcdf87022010-06-29 17:53:46 +00006660/// \brief Retrieve the special "std" namespace, which may require us to
6661/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006662NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006663 if (!StdNamespace) {
6664 // The "std" namespace has not yet been defined, so build one implicitly.
6665 StdNamespace = NamespaceDecl::Create(Context,
6666 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006667 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006668 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006669 &PP.getIdentifierTable().get("std"),
6670 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006671 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006672 }
6673
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006674 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006675}
6676
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006677bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006678 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006679 "Looking for std::initializer_list outside of C++.");
6680
6681 // We're looking for implicit instantiations of
6682 // template <typename E> class std::initializer_list.
6683
6684 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6685 return false;
6686
Sebastian Redl43144e72012-01-17 22:49:58 +00006687 ClassTemplateDecl *Template = 0;
6688 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006689
Sebastian Redl43144e72012-01-17 22:49:58 +00006690 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006691
Sebastian Redl43144e72012-01-17 22:49:58 +00006692 ClassTemplateSpecializationDecl *Specialization =
6693 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6694 if (!Specialization)
6695 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006696
Sebastian Redl43144e72012-01-17 22:49:58 +00006697 Template = Specialization->getSpecializedTemplate();
6698 Arguments = Specialization->getTemplateArgs().data();
6699 } else if (const TemplateSpecializationType *TST =
6700 Ty->getAs<TemplateSpecializationType>()) {
6701 Template = dyn_cast_or_null<ClassTemplateDecl>(
6702 TST->getTemplateName().getAsTemplateDecl());
6703 Arguments = TST->getArgs();
6704 }
6705 if (!Template)
6706 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006707
6708 if (!StdInitializerList) {
6709 // Haven't recognized std::initializer_list yet, maybe this is it.
6710 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6711 if (TemplateClass->getIdentifier() !=
6712 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006713 !getStdNamespace()->InEnclosingNamespaceSetOf(
6714 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006715 return false;
6716 // This is a template called std::initializer_list, but is it the right
6717 // template?
6718 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006719 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006720 return false;
6721 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6722 return false;
6723
6724 // It's the right template.
6725 StdInitializerList = Template;
6726 }
6727
6728 if (Template != StdInitializerList)
6729 return false;
6730
6731 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006732 if (Element)
6733 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006734 return true;
6735}
6736
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006737static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6738 NamespaceDecl *Std = S.getStdNamespace();
6739 if (!Std) {
6740 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6741 return 0;
6742 }
6743
6744 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6745 Loc, Sema::LookupOrdinaryName);
6746 if (!S.LookupQualifiedName(Result, Std)) {
6747 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6748 return 0;
6749 }
6750 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6751 if (!Template) {
6752 Result.suppressDiagnostics();
6753 // We found something weird. Complain about the first thing we found.
6754 NamedDecl *Found = *Result.begin();
6755 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6756 return 0;
6757 }
6758
6759 // We found some template called std::initializer_list. Now verify that it's
6760 // correct.
6761 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006762 if (Params->getMinRequiredArguments() != 1 ||
6763 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006764 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6765 return 0;
6766 }
6767
6768 return Template;
6769}
6770
6771QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6772 if (!StdInitializerList) {
6773 StdInitializerList = LookupStdInitializerList(*this, Loc);
6774 if (!StdInitializerList)
6775 return QualType();
6776 }
6777
6778 TemplateArgumentListInfo Args(Loc, Loc);
6779 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6780 Context.getTrivialTypeSourceInfo(Element,
6781 Loc)));
6782 return Context.getCanonicalType(
6783 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6784}
6785
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006786bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6787 // C++ [dcl.init.list]p2:
6788 // A constructor is an initializer-list constructor if its first parameter
6789 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6790 // std::initializer_list<E> for some type E, and either there are no other
6791 // parameters or else all other parameters have default arguments.
6792 if (Ctor->getNumParams() < 1 ||
6793 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6794 return false;
6795
6796 QualType ArgType = Ctor->getParamDecl(0)->getType();
6797 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6798 ArgType = RT->getPointeeType().getUnqualifiedType();
6799
6800 return isStdInitializerList(ArgType, 0);
6801}
6802
Douglas Gregora172e082011-03-26 22:25:30 +00006803/// \brief Determine whether a using statement is in a context where it will be
6804/// apply in all contexts.
6805static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6806 switch (CurContext->getDeclKind()) {
6807 case Decl::TranslationUnit:
6808 return true;
6809 case Decl::LinkageSpec:
6810 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6811 default:
6812 return false;
6813 }
6814}
6815
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006816namespace {
6817
6818// Callback to only accept typo corrections that are namespaces.
6819class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006820public:
6821 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6822 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006823 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006824 return false;
6825 }
6826};
6827
6828}
6829
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006830static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6831 CXXScopeSpec &SS,
6832 SourceLocation IdentLoc,
6833 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006834 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006835 R.clear();
6836 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006837 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006838 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006839 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006840 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6841 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006842 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006843 S.diagnoseTypo(Corrected,
6844 S.PDiag(diag::err_using_directive_member_suggest)
6845 << Ident << DC << DroppedSpecifier << SS.getRange(),
6846 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006847 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006848 S.diagnoseTypo(Corrected,
6849 S.PDiag(diag::err_using_directive_suggest) << Ident,
6850 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006851 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006852 R.addDecl(Corrected.getCorrectionDecl());
6853 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006854 }
6855 return false;
6856}
6857
John McCall48871652010-08-21 09:40:31 +00006858Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006859 SourceLocation UsingLoc,
6860 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006861 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006862 SourceLocation IdentLoc,
6863 IdentifierInfo *NamespcName,
6864 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006865 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6866 assert(NamespcName && "Invalid NamespcName.");
6867 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006868
6869 // This can only happen along a recovery path.
6870 while (S->getFlags() & Scope::TemplateParamScope)
6871 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006872 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006873
Douglas Gregor889ceb72009-02-03 19:21:40 +00006874 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006875 NestedNameSpecifier *Qualifier = 0;
6876 if (SS.isSet())
6877 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6878
Douglas Gregor34074322009-01-14 22:20:51 +00006879 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006880 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6881 LookupParsedName(R, S, &SS);
6882 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006883 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006884
Douglas Gregorcdf87022010-06-29 17:53:46 +00006885 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006886 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006887 // Allow "using namespace std;" or "using namespace ::std;" even if
6888 // "std" hasn't been defined yet, for GCC compatibility.
6889 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6890 NamespcName->isStr("std")) {
6891 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006892 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006893 R.resolveKind();
6894 }
6895 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006896 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006897 }
6898
John McCall9f3059a2009-10-09 21:13:30 +00006899 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006900 NamedDecl *Named = R.getFoundDecl();
6901 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6902 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006903 // C++ [namespace.udir]p1:
6904 // A using-directive specifies that the names in the nominated
6905 // namespace can be used in the scope in which the
6906 // using-directive appears after the using-directive. During
6907 // unqualified name lookup (3.4.1), the names appear as if they
6908 // were declared in the nearest enclosing namespace which
6909 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006910 // namespace. [Note: in this context, "contains" means "contains
6911 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006912
6913 // Find enclosing context containing both using-directive and
6914 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006915 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006916 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6917 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6918 CommonAncestor = CommonAncestor->getParent();
6919
Sebastian Redla6602e92009-11-23 15:34:23 +00006920 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006921 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006922 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006923
Douglas Gregora172e082011-03-26 22:25:30 +00006924 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006925 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006926 Diag(IdentLoc, diag::warn_using_directive_in_header);
6927 }
6928
Douglas Gregor889ceb72009-02-03 19:21:40 +00006929 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006930 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006931 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006932 }
6933
Richard Smith54ecd982013-02-20 19:22:51 +00006934 if (UDir)
6935 ProcessDeclAttributeList(S, UDir, AttrList);
6936
John McCall48871652010-08-21 09:40:31 +00006937 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006938}
6939
6940void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00006941 // If the scope has an associated entity and the using directive is at
6942 // namespace or translation unit scope, add the UsingDirectiveDecl into
6943 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00006944 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00006945 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006946 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006947 else
Richard Smith05afe5e2012-03-13 03:12:56 +00006948 // Otherwise, it is at block sope. The using-directives will affect lookup
6949 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00006950 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006951}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006952
Douglas Gregorfec52632009-06-20 00:51:54 +00006953
John McCall48871652010-08-21 09:40:31 +00006954Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006955 AccessSpecifier AS,
6956 bool HasUsingKeyword,
6957 SourceLocation UsingLoc,
6958 CXXScopeSpec &SS,
6959 UnqualifiedId &Name,
6960 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00006961 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00006962 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006963 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006964
Douglas Gregor220f4272009-11-04 16:30:06 +00006965 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006966 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006967 case UnqualifiedId::IK_Identifier:
6968 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006969 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006970 case UnqualifiedId::IK_ConversionFunctionId:
6971 break;
6972
6973 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006974 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00006975 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006976 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006977 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00006978 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00006979 diag::err_using_decl_constructor)
6980 << SS.getRange();
6981
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006982 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00006983
John McCall48871652010-08-21 09:40:31 +00006984 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006985
6986 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006987 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00006988 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006989 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006990
6991 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006992 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00006993 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006994 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006995 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006996
6997 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6998 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006999 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007000 return 0;
John McCall3969e302009-12-08 07:46:18 +00007001
Richard Smithc2bc61b2013-03-18 21:12:30 +00007002 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007003 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007004 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007005 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7006 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007007 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007008 }
7009
Douglas Gregorc4356532010-12-16 00:46:58 +00007010 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7011 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7012 return 0;
7013
John McCall3f746822009-11-17 05:59:44 +00007014 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007015 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007016 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007017 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007018 if (UD)
7019 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007020
John McCall48871652010-08-21 09:40:31 +00007021 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007022}
7023
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007024/// \brief Determine whether a using declaration considers the given
7025/// declarations as "equivalent", e.g., if they are redeclarations of
7026/// the same entity or are both typedefs of the same type.
7027static bool
7028IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
7029 bool &SuppressRedeclaration) {
7030 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
7031 SuppressRedeclaration = false;
7032 return true;
7033 }
7034
Richard Smithdda56e42011-04-15 14:24:37 +00007035 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7036 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007037 SuppressRedeclaration = true;
7038 return Context.hasSameType(TD1->getUnderlyingType(),
7039 TD2->getUnderlyingType());
7040 }
7041
7042 return false;
7043}
7044
7045
John McCall84d87672009-12-10 09:41:52 +00007046/// Determines whether to create a using shadow decl for a particular
7047/// decl, given the set of decls existing prior to this using lookup.
7048bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7049 const LookupResult &Previous) {
7050 // Diagnose finding a decl which is not from a base class of the
7051 // current class. We do this now because there are cases where this
7052 // function will silently decide not to build a shadow decl, which
7053 // will pre-empt further diagnostics.
7054 //
7055 // We don't need to do this in C++0x because we do the check once on
7056 // the qualifier.
7057 //
7058 // FIXME: diagnose the following if we care enough:
7059 // struct A { int foo; };
7060 // struct B : A { using A::foo; };
7061 // template <class T> struct C : A {};
7062 // template <class T> struct D : C<T> { using B::foo; } // <---
7063 // This is invalid (during instantiation) in C++03 because B::foo
7064 // resolves to the using decl in B, which is not a base class of D<T>.
7065 // We can't diagnose it immediately because C<T> is an unknown
7066 // specialization. The UsingShadowDecl in D<T> then points directly
7067 // to A::foo, which will look well-formed when we instantiate.
7068 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007069 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007070 DeclContext *OrigDC = Orig->getDeclContext();
7071
7072 // Handle enums and anonymous structs.
7073 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7074 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7075 while (OrigRec->isAnonymousStructOrUnion())
7076 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7077
7078 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7079 if (OrigDC == CurContext) {
7080 Diag(Using->getLocation(),
7081 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007082 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007083 Diag(Orig->getLocation(), diag::note_using_decl_target);
7084 return true;
7085 }
7086
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007087 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007088 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007089 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007090 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007091 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007092 Diag(Orig->getLocation(), diag::note_using_decl_target);
7093 return true;
7094 }
7095 }
7096
7097 if (Previous.empty()) return false;
7098
7099 NamedDecl *Target = Orig;
7100 if (isa<UsingShadowDecl>(Target))
7101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7102
John McCalla17e83e2009-12-11 02:33:26 +00007103 // If the target happens to be one of the previous declarations, we
7104 // don't have a conflict.
7105 //
7106 // FIXME: but we might be increasing its access, in which case we
7107 // should redeclare it.
7108 NamedDecl *NonTag = 0, *Tag = 0;
7109 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7110 I != E; ++I) {
7111 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007112 bool Result;
7113 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7114 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00007115
7116 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7117 }
7118
John McCall84d87672009-12-10 09:41:52 +00007119 if (Target->isFunctionOrFunctionTemplate()) {
7120 FunctionDecl *FD;
7121 if (isa<FunctionTemplateDecl>(Target))
7122 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7123 else
7124 FD = cast<FunctionDecl>(Target);
7125
7126 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007127 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007128 case Ovl_Overload:
7129 return false;
7130
7131 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007132 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007133 break;
7134
7135 // We found a decl with the exact signature.
7136 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007137 // If we're in a record, we want to hide the target, so we
7138 // return true (without a diagnostic) to tell the caller not to
7139 // build a shadow decl.
7140 if (CurContext->isRecord())
7141 return true;
7142
7143 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007144 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007145 break;
7146 }
7147
7148 Diag(Target->getLocation(), diag::note_using_decl_target);
7149 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7150 return true;
7151 }
7152
7153 // Target is not a function.
7154
John McCall84d87672009-12-10 09:41:52 +00007155 if (isa<TagDecl>(Target)) {
7156 // No conflict between a tag and a non-tag.
7157 if (!Tag) return false;
7158
John McCalle29c5cd2009-12-10 19:51:03 +00007159 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007160 Diag(Target->getLocation(), diag::note_using_decl_target);
7161 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7162 return true;
7163 }
7164
7165 // No conflict between a tag and a non-tag.
7166 if (!NonTag) return false;
7167
John McCalle29c5cd2009-12-10 19:51:03 +00007168 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007169 Diag(Target->getLocation(), diag::note_using_decl_target);
7170 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7171 return true;
7172}
7173
John McCall3f746822009-11-17 05:59:44 +00007174/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007175UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007176 UsingDecl *UD,
7177 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00007178
7179 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007180 NamedDecl *Target = Orig;
7181 if (isa<UsingShadowDecl>(Target)) {
7182 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7183 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007184 }
7185
7186 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007187 = UsingShadowDecl::Create(Context, CurContext,
7188 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007189 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00007190
7191 Shadow->setAccess(UD->getAccess());
7192 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7193 Shadow->setInvalidDecl();
7194
John McCall3f746822009-11-17 05:59:44 +00007195 if (S)
John McCall3969e302009-12-08 07:46:18 +00007196 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007197 else
John McCall3969e302009-12-08 07:46:18 +00007198 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007199
John McCall3969e302009-12-08 07:46:18 +00007200
John McCall84d87672009-12-10 09:41:52 +00007201 return Shadow;
7202}
John McCall3969e302009-12-08 07:46:18 +00007203
John McCall84d87672009-12-10 09:41:52 +00007204/// Hides a using shadow declaration. This is required by the current
7205/// using-decl implementation when a resolvable using declaration in a
7206/// class is followed by a declaration which would hide or override
7207/// one or more of the using decl's targets; for example:
7208///
7209/// struct Base { void foo(int); };
7210/// struct Derived : Base {
7211/// using Base::foo;
7212/// void foo(int);
7213/// };
7214///
7215/// The governing language is C++03 [namespace.udecl]p12:
7216///
7217/// When a using-declaration brings names from a base class into a
7218/// derived class scope, member functions in the derived class
7219/// override and/or hide member functions with the same name and
7220/// parameter types in a base class (rather than conflicting).
7221///
7222/// There are two ways to implement this:
7223/// (1) optimistically create shadow decls when they're not hidden
7224/// by existing declarations, or
7225/// (2) don't create any shadow decls (or at least don't make them
7226/// visible) until we've fully parsed/instantiated the class.
7227/// The problem with (1) is that we might have to retroactively remove
7228/// a shadow decl, which requires several O(n) operations because the
7229/// decl structures are (very reasonably) not designed for removal.
7230/// (2) avoids this but is very fiddly and phase-dependent.
7231void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007232 if (Shadow->getDeclName().getNameKind() ==
7233 DeclarationName::CXXConversionFunctionName)
7234 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7235
John McCall84d87672009-12-10 09:41:52 +00007236 // Remove it from the DeclContext...
7237 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007238
John McCall84d87672009-12-10 09:41:52 +00007239 // ...and the scope, if applicable...
7240 if (S) {
John McCall48871652010-08-21 09:40:31 +00007241 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007242 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007243 }
7244
John McCall84d87672009-12-10 09:41:52 +00007245 // ...and the using decl.
7246 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7247
7248 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007249 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007250}
7251
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007252namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007253class UsingValidatorCCC : public CorrectionCandidateCallback {
7254public:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007255 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7256 : HasTypenameKeyword(HasTypenameKeyword),
7257 IsInstantiation(IsInstantiation) {}
7258
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007259 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7260 NamedDecl *ND = Candidate.getCorrectionDecl();
7261
7262 // Keywords are not valid here.
7263 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007264 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007265
7266 // Completely unqualified names are invalid for a 'using' declaration.
7267 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7268 return false;
7269
7270 if (isa<TypeDecl>(ND))
7271 return HasTypenameKeyword || !IsInstantiation;
7272
7273 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007274 }
7275
7276private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007277 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007278 bool IsInstantiation;
7279};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007280} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007281
John McCalle61f2ba2009-11-18 02:36:19 +00007282/// Builds a using declaration.
7283///
7284/// \param IsInstantiation - Whether this call arises from an
7285/// instantiation of an unresolved using declaration. We treat
7286/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007287NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7288 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007289 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007290 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007291 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007292 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007293 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007294 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007295 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007296 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007297 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007298
Anders Carlssonf038fc22009-08-28 05:49:21 +00007299 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007300
Anders Carlsson59140b32009-08-28 03:16:11 +00007301 if (SS.isEmpty()) {
7302 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007303 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007304 }
Mike Stump11289f42009-09-09 15:08:12 +00007305
John McCall84d87672009-12-10 09:41:52 +00007306 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007307 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007308 ForRedeclaration);
7309 Previous.setHideTags(false);
7310 if (S) {
7311 LookupName(Previous, S);
7312
7313 // It is really dumb that we have to do this.
7314 LookupResult::Filter F = Previous.makeFilter();
7315 while (F.hasNext()) {
7316 NamedDecl *D = F.next();
7317 if (!isDeclInScope(D, CurContext, S))
7318 F.erase();
7319 }
7320 F.done();
7321 } else {
7322 assert(IsInstantiation && "no scope in non-instantiation");
7323 assert(CurContext->isRecord() && "scope not record in instantiation");
7324 LookupQualifiedName(Previous, CurContext);
7325 }
7326
John McCall84d87672009-12-10 09:41:52 +00007327 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007328 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7329 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007330 return 0;
7331
7332 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007333 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7334 return 0;
7335
John McCall84c16cf2009-11-12 03:15:40 +00007336 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007337 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007338 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007339 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007340 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007341 // FIXME: not all declaration name kinds are legal here
7342 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7343 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007344 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007345 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007346 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007347 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7348 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007349 }
John McCallb96ec562009-12-04 22:46:56 +00007350 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007351 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007352 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007353 }
John McCallb96ec562009-12-04 22:46:56 +00007354 D->setAccess(AS);
7355 CurContext->addDecl(D);
7356
7357 if (!LookupContext) return D;
7358 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007359
John McCall0b66eb32010-05-01 00:40:08 +00007360 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007361 UD->setInvalidDecl();
7362 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007363 }
7364
Richard Smith23d55872012-04-02 01:30:27 +00007365 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007366 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007367 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007368 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007369 return UD;
7370 }
7371
7372 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007373
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007374 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007375
John McCall3969e302009-12-08 07:46:18 +00007376 // Unlike most lookups, we don't always want to hide tag
7377 // declarations: tag names are visible through the using declaration
7378 // even if hidden by ordinary names, *except* in a dependent context
7379 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007380 if (!IsInstantiation)
7381 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007382
John McCall5dadb652012-04-07 03:04:20 +00007383 // For the purposes of this lookup, we have a base object type
7384 // equal to that of the current context.
7385 if (CurContext->isRecord()) {
7386 R.setBaseObjectType(
7387 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7388 }
7389
John McCall27b18f82009-11-17 02:14:36 +00007390 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007391
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007392 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007393 if (R.empty()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007394 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007395 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7396 R.getLookupKind(), S, &SS, CCC)){
7397 // We reject any correction for which ND would be NULL.
7398 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007399 R.setLookupName(Corrected.getCorrection());
7400 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007401 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007402 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007403 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7404 << NameInfo.getName() << LookupContext << 0
7405 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007406 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007407 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007408 << NameInfo.getName() << LookupContext << SS.getRange();
7409 UD->setInvalidDecl();
7410 return UD;
7411 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007412 }
7413
John McCallb96ec562009-12-04 22:46:56 +00007414 if (R.isAmbiguous()) {
7415 UD->setInvalidDecl();
7416 return UD;
7417 }
Mike Stump11289f42009-09-09 15:08:12 +00007418
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007419 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007420 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007421 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007422 Diag(IdentLoc, diag::err_using_typename_non_type);
7423 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7424 Diag((*I)->getUnderlyingDecl()->getLocation(),
7425 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007426 UD->setInvalidDecl();
7427 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007428 }
7429 } else {
7430 // If we asked for a non-typename and we got a type, error out,
7431 // but only if this is an instantiation of an unresolved using
7432 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007433 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007434 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7435 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007436 UD->setInvalidDecl();
7437 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007438 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007439 }
7440
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007441 // C++0x N2914 [namespace.udecl]p6:
7442 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007443 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007444 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7445 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007446 UD->setInvalidDecl();
7447 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007448 }
Mike Stump11289f42009-09-09 15:08:12 +00007449
John McCall84d87672009-12-10 09:41:52 +00007450 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7451 if (!CheckUsingShadowDecl(UD, *I, Previous))
7452 BuildUsingShadowDecl(S, UD, *I);
7453 }
John McCall3f746822009-11-17 05:59:44 +00007454
7455 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007456}
7457
Sebastian Redl08905022011-02-05 19:23:19 +00007458/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007459bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007460 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007461
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007462 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007463 assert(SourceType &&
7464 "Using decl naming constructor doesn't have type in scope spec.");
7465 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7466
7467 // Check whether the named type is a direct base class.
7468 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7469 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7470 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7471 BaseIt != BaseE; ++BaseIt) {
7472 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7473 if (CanonicalSourceType == BaseType)
7474 break;
Richard Smith23d55872012-04-02 01:30:27 +00007475 if (BaseIt->getType()->isDependentType())
7476 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007477 }
7478
7479 if (BaseIt == BaseE) {
7480 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007481 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007482 diag::err_using_decl_constructor_not_in_direct_base)
7483 << UD->getNameInfo().getSourceRange()
7484 << QualType(SourceType, 0) << TargetClass;
7485 return true;
7486 }
7487
Richard Smith23d55872012-04-02 01:30:27 +00007488 if (!CurContext->isDependentContext())
7489 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007490
7491 return false;
7492}
7493
John McCall84d87672009-12-10 09:41:52 +00007494/// Checks that the given using declaration is not an invalid
7495/// redeclaration. Note that this is checking only for the using decl
7496/// itself, not for any ill-formedness among the UsingShadowDecls.
7497bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007498 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007499 const CXXScopeSpec &SS,
7500 SourceLocation NameLoc,
7501 const LookupResult &Prev) {
7502 // C++03 [namespace.udecl]p8:
7503 // C++0x [namespace.udecl]p10:
7504 // A using-declaration is a declaration and can therefore be used
7505 // repeatedly where (and only where) multiple declarations are
7506 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007507 //
John McCall032092f2010-11-29 18:01:58 +00007508 // That's in non-member contexts.
7509 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007510 return false;
7511
7512 NestedNameSpecifier *Qual
7513 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7514
7515 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7516 NamedDecl *D = *I;
7517
7518 bool DTypename;
7519 NestedNameSpecifier *DQual;
7520 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007521 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007522 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007523 } else if (UnresolvedUsingValueDecl *UD
7524 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7525 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007526 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007527 } else if (UnresolvedUsingTypenameDecl *UD
7528 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7529 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007530 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007531 } else continue;
7532
7533 // using decls differ if one says 'typename' and the other doesn't.
7534 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007535 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007536
7537 // using decls differ if they name different scopes (but note that
7538 // template instantiation can cause this check to trigger when it
7539 // didn't before instantiation).
7540 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7541 Context.getCanonicalNestedNameSpecifier(DQual))
7542 continue;
7543
7544 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007545 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007546 return true;
7547 }
7548
7549 return false;
7550}
7551
John McCall3969e302009-12-08 07:46:18 +00007552
John McCallb96ec562009-12-04 22:46:56 +00007553/// Checks that the given nested-name qualifier used in a using decl
7554/// in the current context is appropriately related to the current
7555/// scope. If an error is found, diagnoses it and returns true.
7556bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7557 const CXXScopeSpec &SS,
7558 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007559 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007560
John McCall3969e302009-12-08 07:46:18 +00007561 if (!CurContext->isRecord()) {
7562 // C++03 [namespace.udecl]p3:
7563 // C++0x [namespace.udecl]p8:
7564 // A using-declaration for a class member shall be a member-declaration.
7565
7566 // If we weren't able to compute a valid scope, it must be a
7567 // dependent class scope.
7568 if (!NamedContext || NamedContext->isRecord()) {
7569 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7570 << SS.getRange();
7571 return true;
7572 }
7573
7574 // Otherwise, everything is known to be fine.
7575 return false;
7576 }
7577
7578 // The current scope is a record.
7579
7580 // If the named context is dependent, we can't decide much.
7581 if (!NamedContext) {
7582 // FIXME: in C++0x, we can diagnose if we can prove that the
7583 // nested-name-specifier does not refer to a base class, which is
7584 // still possible in some cases.
7585
7586 // Otherwise we have to conservatively report that things might be
7587 // okay.
7588 return false;
7589 }
7590
7591 if (!NamedContext->isRecord()) {
7592 // Ideally this would point at the last name in the specifier,
7593 // but we don't have that level of source info.
7594 Diag(SS.getRange().getBegin(),
7595 diag::err_using_decl_nested_name_specifier_is_not_class)
7596 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7597 return true;
7598 }
7599
Douglas Gregor7c842292010-12-21 07:41:49 +00007600 if (!NamedContext->isDependentContext() &&
7601 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7602 return true;
7603
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007604 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007605 // C++0x [namespace.udecl]p3:
7606 // In a using-declaration used as a member-declaration, the
7607 // nested-name-specifier shall name a base class of the class
7608 // being defined.
7609
7610 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7611 cast<CXXRecordDecl>(NamedContext))) {
7612 if (CurContext == NamedContext) {
7613 Diag(NameLoc,
7614 diag::err_using_decl_nested_name_specifier_is_current_class)
7615 << SS.getRange();
7616 return true;
7617 }
7618
7619 Diag(SS.getRange().getBegin(),
7620 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7621 << (NestedNameSpecifier*) SS.getScopeRep()
7622 << cast<CXXRecordDecl>(CurContext)
7623 << SS.getRange();
7624 return true;
7625 }
7626
7627 return false;
7628 }
7629
7630 // C++03 [namespace.udecl]p4:
7631 // A using-declaration used as a member-declaration shall refer
7632 // to a member of a base class of the class being defined [etc.].
7633
7634 // Salient point: SS doesn't have to name a base class as long as
7635 // lookup only finds members from base classes. Therefore we can
7636 // diagnose here only if we can prove that that can't happen,
7637 // i.e. if the class hierarchies provably don't intersect.
7638
7639 // TODO: it would be nice if "definitely valid" results were cached
7640 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7641 // need to be repeated.
7642
7643 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007644 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007645
7646 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7647 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7648 Data->Bases.insert(Base);
7649 return true;
7650 }
7651
7652 bool hasDependentBases(const CXXRecordDecl *Class) {
7653 return !Class->forallBases(collect, this);
7654 }
7655
7656 /// Returns true if the base is dependent or is one of the
7657 /// accumulated base classes.
7658 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7659 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7660 return !Data->Bases.count(Base);
7661 }
7662
7663 bool mightShareBases(const CXXRecordDecl *Class) {
7664 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7665 }
7666 };
7667
7668 UserData Data;
7669
7670 // Returns false if we find a dependent base.
7671 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7672 return false;
7673
7674 // Returns false if the class has a dependent base or if it or one
7675 // of its bases is present in the base set of the current context.
7676 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7677 return false;
7678
7679 Diag(SS.getRange().getBegin(),
7680 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7681 << (NestedNameSpecifier*) SS.getScopeRep()
7682 << cast<CXXRecordDecl>(CurContext)
7683 << SS.getRange();
7684
7685 return true;
John McCallb96ec562009-12-04 22:46:56 +00007686}
7687
Richard Smithdda56e42011-04-15 14:24:37 +00007688Decl *Sema::ActOnAliasDeclaration(Scope *S,
7689 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007690 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007691 SourceLocation UsingLoc,
7692 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007693 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007694 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007695 // Skip up to the relevant declaration scope.
7696 while (S->getFlags() & Scope::TemplateParamScope)
7697 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007698 assert((S->getFlags() & Scope::DeclScope) &&
7699 "got alias-declaration outside of declaration scope");
7700
7701 if (Type.isInvalid())
7702 return 0;
7703
7704 bool Invalid = false;
7705 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7706 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007707 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007708
7709 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7710 return 0;
7711
7712 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007713 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007714 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007715 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7716 TInfo->getTypeLoc().getBeginLoc());
7717 }
Richard Smithdda56e42011-04-15 14:24:37 +00007718
7719 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7720 LookupName(Previous, S);
7721
7722 // Warn about shadowing the name of a template parameter.
7723 if (Previous.isSingleResult() &&
7724 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007725 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007726 Previous.clear();
7727 }
7728
7729 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7730 "name in alias declaration must be an identifier");
7731 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7732 Name.StartLocation,
7733 Name.Identifier, TInfo);
7734
7735 NewTD->setAccess(AS);
7736
7737 if (Invalid)
7738 NewTD->setInvalidDecl();
7739
Richard Smith54ecd982013-02-20 19:22:51 +00007740 ProcessDeclAttributeList(S, NewTD, AttrList);
7741
Richard Smith3f1b5d02011-05-05 21:57:07 +00007742 CheckTypedefForVariablyModifiedType(S, NewTD);
7743 Invalid |= NewTD->isInvalidDecl();
7744
Richard Smithdda56e42011-04-15 14:24:37 +00007745 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007746
7747 NamedDecl *NewND;
7748 if (TemplateParamLists.size()) {
7749 TypeAliasTemplateDecl *OldDecl = 0;
7750 TemplateParameterList *OldTemplateParams = 0;
7751
7752 if (TemplateParamLists.size() != 1) {
7753 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007754 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7755 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007756 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007757 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007758
7759 // Only consider previous declarations in the same scope.
7760 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7761 /*ExplicitInstantiationOrSpecialization*/false);
7762 if (!Previous.empty()) {
7763 Redeclaration = true;
7764
7765 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7766 if (!OldDecl && !Invalid) {
7767 Diag(UsingLoc, diag::err_redefinition_different_kind)
7768 << Name.Identifier;
7769
7770 NamedDecl *OldD = Previous.getRepresentativeDecl();
7771 if (OldD->getLocation().isValid())
7772 Diag(OldD->getLocation(), diag::note_previous_definition);
7773
7774 Invalid = true;
7775 }
7776
7777 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7778 if (TemplateParameterListsAreEqual(TemplateParams,
7779 OldDecl->getTemplateParameters(),
7780 /*Complain=*/true,
7781 TPL_TemplateMatch))
7782 OldTemplateParams = OldDecl->getTemplateParameters();
7783 else
7784 Invalid = true;
7785
7786 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7787 if (!Invalid &&
7788 !Context.hasSameType(OldTD->getUnderlyingType(),
7789 NewTD->getUnderlyingType())) {
7790 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7791 // but we can't reasonably accept it.
7792 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7793 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7794 if (OldTD->getLocation().isValid())
7795 Diag(OldTD->getLocation(), diag::note_previous_definition);
7796 Invalid = true;
7797 }
7798 }
7799 }
7800
7801 // Merge any previous default template arguments into our parameters,
7802 // and check the parameter list.
7803 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7804 TPC_TypeAliasTemplate))
7805 return 0;
7806
7807 TypeAliasTemplateDecl *NewDecl =
7808 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7809 Name.Identifier, TemplateParams,
7810 NewTD);
7811
7812 NewDecl->setAccess(AS);
7813
7814 if (Invalid)
7815 NewDecl->setInvalidDecl();
7816 else if (OldDecl)
7817 NewDecl->setPreviousDeclaration(OldDecl);
7818
7819 NewND = NewDecl;
7820 } else {
7821 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7822 NewND = NewTD;
7823 }
Richard Smithdda56e42011-04-15 14:24:37 +00007824
7825 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007826 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007827
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007828 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007829 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007830}
7831
John McCall48871652010-08-21 09:40:31 +00007832Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007833 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007834 SourceLocation AliasLoc,
7835 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007836 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007837 SourceLocation IdentLoc,
7838 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007839
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007840 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007841 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7842 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007843
Anders Carlssondca83c42009-03-28 06:23:46 +00007844 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007845 NamedDecl *PrevDecl
7846 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7847 ForRedeclaration);
7848 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7849 PrevDecl = 0;
7850
7851 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007852 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007853 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007854 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007855 // FIXME: At some point, we'll want to create the (redundant)
7856 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007857 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007858 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007859 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007860 }
Mike Stump11289f42009-09-09 15:08:12 +00007861
Anders Carlssondca83c42009-03-28 06:23:46 +00007862 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7863 diag::err_redefinition_different_kind;
7864 Diag(AliasLoc, DiagID) << Alias;
7865 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007866 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007867 }
7868
John McCall27b18f82009-11-17 02:14:36 +00007869 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007870 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007871
John McCall9f3059a2009-10-09 21:13:30 +00007872 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007873 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007874 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007875 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007876 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007877 }
Mike Stump11289f42009-09-09 15:08:12 +00007878
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007879 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007880 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00007881 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00007882 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007883
John McCalld8d0d432010-02-16 06:53:13 +00007884 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00007885 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00007886}
7887
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007888Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00007889Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7890 CXXMethodDecl *MD) {
7891 CXXRecordDecl *ClassDecl = MD->getParent();
7892
Douglas Gregor6d880b12010-07-01 22:31:05 +00007893 // C++ [except.spec]p14:
7894 // An implicitly declared special member function (Clause 12) shall have an
7895 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00007896 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007897 if (ClassDecl->isInvalidDecl())
7898 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00007899
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007900 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007901 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7902 BEnd = ClassDecl->bases_end();
7903 B != BEnd; ++B) {
7904 if (B->isVirtual()) // Handled below.
7905 continue;
7906
Douglas Gregor9672f922010-07-03 00:47:00 +00007907 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7908 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007909 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7910 // If this is a deleted function, add it anyway. This might be conformant
7911 // with the standard. This might not. I'm not sure. It might not matter.
7912 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007913 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007914 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007915 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007916
7917 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007918 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7919 BEnd = ClassDecl->vbases_end();
7920 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007921 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7922 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007923 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7924 // If this is a deleted function, add it anyway. This might be conformant
7925 // with the standard. This might not. I'm not sure. It might not matter.
7926 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007927 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007928 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007929 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007930
7931 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007932 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7933 FEnd = ClassDecl->field_end();
7934 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007935 if (F->hasInClassInitializer()) {
7936 if (Expr *E = F->getInClassInitializer())
7937 ExceptSpec.CalledExpr(E);
7938 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00007939 // DR1351:
7940 // If the brace-or-equal-initializer of a non-static data member
7941 // invokes a defaulted default constructor of its class or of an
7942 // enclosing class in a potentially evaluated subexpression, the
7943 // program is ill-formed.
7944 //
7945 // This resolution is unworkable: the exception specification of the
7946 // default constructor can be needed in an unevaluated context, in
7947 // particular, in the operand of a noexcept-expression, and we can be
7948 // unable to compute an exception specification for an enclosed class.
7949 //
7950 // We do not allow an in-class initializer to require the evaluation
7951 // of the exception specification for any in-class initializer whose
7952 // definition is not lexically complete.
7953 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00007954 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007955 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007956 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7957 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7958 // If this is a deleted function, add it anyway. This might be conformant
7959 // with the standard. This might not. I'm not sure. It might not matter.
7960 // In particular, the problem is that this function never gets called. It
7961 // might just be ill-formed because this function attempts to refer to
7962 // a deleted function here.
7963 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00007964 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007965 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007966 }
John McCalldb40c7f2010-12-14 08:05:40 +00007967
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007968 return ExceptSpec;
7969}
7970
Richard Smithc2bc61b2013-03-18 21:12:30 +00007971Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00007972Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7973 CXXRecordDecl *ClassDecl = CD->getParent();
7974
7975 // C++ [except.spec]p14:
7976 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00007977 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00007978 if (ClassDecl->isInvalidDecl())
7979 return ExceptSpec;
7980
7981 // Inherited constructor.
7982 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7983 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7984 // FIXME: Copying or moving the parameters could add extra exceptions to the
7985 // set, as could the default arguments for the inherited constructor. This
7986 // will be addressed when we implement the resolution of core issue 1351.
7987 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7988
7989 // Direct base-class constructors.
7990 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7991 BEnd = ClassDecl->bases_end();
7992 B != BEnd; ++B) {
7993 if (B->isVirtual()) // Handled below.
7994 continue;
7995
7996 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7997 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7998 if (BaseClassDecl == InheritedDecl)
7999 continue;
8000 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8001 if (Constructor)
8002 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8003 }
8004 }
8005
8006 // Virtual base-class constructors.
8007 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8008 BEnd = ClassDecl->vbases_end();
8009 B != BEnd; ++B) {
8010 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8011 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8012 if (BaseClassDecl == InheritedDecl)
8013 continue;
8014 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8015 if (Constructor)
8016 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8017 }
8018 }
8019
8020 // Field constructors.
8021 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8022 FEnd = ClassDecl->field_end();
8023 F != FEnd; ++F) {
8024 if (F->hasInClassInitializer()) {
8025 if (Expr *E = F->getInClassInitializer())
8026 ExceptSpec.CalledExpr(E);
8027 else if (!F->isInvalidDecl())
8028 Diag(CD->getLocation(),
8029 diag::err_in_class_initializer_references_def_ctor) << CD;
8030 } else if (const RecordType *RecordTy
8031 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8032 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8033 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8034 if (Constructor)
8035 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8036 }
8037 }
8038
Richard Smithc2bc61b2013-03-18 21:12:30 +00008039 return ExceptSpec;
8040}
8041
Richard Smith8bf22e52012-11-29 01:34:07 +00008042namespace {
8043/// RAII object to register a special member as being currently declared.
8044struct DeclaringSpecialMember {
8045 Sema &S;
8046 Sema::SpecialMemberDecl D;
8047 bool WasAlreadyBeingDeclared;
8048
8049 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8050 : S(S), D(RD, CSM) {
8051 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8052 if (WasAlreadyBeingDeclared)
8053 // This almost never happens, but if it does, ensure that our cache
8054 // doesn't contain a stale result.
8055 S.SpecialMemberCache.clear();
8056
8057 // FIXME: Register a note to be produced if we encounter an error while
8058 // declaring the special member.
8059 }
8060 ~DeclaringSpecialMember() {
8061 if (!WasAlreadyBeingDeclared)
8062 S.SpecialMembersBeingDeclared.erase(D);
8063 }
8064
8065 /// \brief Are we already trying to declare this special member?
8066 bool isAlreadyBeingDeclared() const {
8067 return WasAlreadyBeingDeclared;
8068 }
8069};
8070}
8071
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008072CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8073 CXXRecordDecl *ClassDecl) {
8074 // C++ [class.ctor]p5:
8075 // A default constructor for a class X is a constructor of class X
8076 // that can be called without an argument. If there is no
8077 // user-declared constructor for class X, a default constructor is
8078 // implicitly declared. An implicitly-declared default constructor
8079 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008080 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008081 "Should not build implicit default constructor!");
8082
Richard Smith8bf22e52012-11-29 01:34:07 +00008083 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8084 if (DSM.isAlreadyBeingDeclared())
8085 return 0;
8086
Richard Smithb5800092012-06-10 05:43:50 +00008087 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8088 CXXDefaultConstructor,
8089 false);
8090
Douglas Gregor6d880b12010-07-01 22:31:05 +00008091 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008092 CanQualType ClassType
8093 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008094 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008095 DeclarationName Name
8096 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008097 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008098 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008099 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008100 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008101 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008102 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008103 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008104 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008105
8106 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008107 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008108 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008109
Richard Smith6b02d462012-12-08 08:32:28 +00008110 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8111 // constructors is easy to compute.
8112 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8113
8114 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008115 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008116
Douglas Gregor9672f922010-07-03 00:47:00 +00008117 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008118 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008119
Douglas Gregor0be31a22010-07-02 17:43:08 +00008120 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008121 PushOnScopeChains(DefaultCon, S, false);
8122 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008123
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008124 return DefaultCon;
8125}
8126
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008127void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8128 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008129 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008130 !Constructor->doesThisDeclarationHaveABody() &&
8131 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008132 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008133
Anders Carlsson423f5d82010-04-23 16:04:08 +00008134 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008135 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008136
Eli Friedmaneaf34142012-10-18 20:14:08 +00008137 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008138 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008139 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008140 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008141 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008142 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008143 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008144 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008145 }
Douglas Gregor73193272010-09-20 16:48:21 +00008146
8147 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008148 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008149
Eli Friedman276dd182013-09-05 00:02:25 +00008150 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008151 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008152
8153 if (ASTMutationListener *L = getASTMutationListener()) {
8154 L->CompletedImplicitDefinition(Constructor);
8155 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008156}
8157
Richard Smith938f40b2011-06-11 17:19:42 +00008158void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smithbd305122012-12-11 01:14:52 +00008159 // Check that any explicitly-defaulted methods have exception specifications
8160 // compatible with their implicit exception specifications.
8161 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Trieu406e65c2013-09-20 03:03:06 +00008162
8163 // Once all the member initializers are processed, perform checks to see if
8164 // any unintialized use is happeneing.
8165 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
8166 D->getLocation())
8167 == DiagnosticsEngine::Ignored)
8168 return;
8169
8170 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
8171 if (!RD) return;
8172
8173 // Holds fields that are uninitialized.
8174 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
8175
8176 // In the beginning, every field is uninitialized.
8177 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8178 I != E; ++I) {
8179 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
8180 UninitializedFields.insert(FD);
8181 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
8182 UninitializedFields.insert(IFD->getAnonField());
8183 }
8184 }
8185
8186 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8187 I != E; ++I) {
8188 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
8189 if (!FD)
8190 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
8191 FD = IFD->getAnonField();
8192
8193 if (!FD)
8194 continue;
8195
8196 Expr *InitExpr = FD->getInClassInitializer();
8197 if (!InitExpr) {
8198 // Uninitialized reference types will give an error.
8199 // Record types with an initializer are default initialized.
8200 QualType FieldType = FD->getType();
8201 if (FieldType->isReferenceType() || FieldType->isRecordType())
8202 UninitializedFields.erase(FD);
8203 continue;
8204 }
8205
8206 CheckInitExprContainsUninitializedFields(
8207 *this, InitExpr, FD, UninitializedFields,
8208 UninitializedFields.count(FD)/*WarnOnSelfReference*/);
8209
8210 UninitializedFields.erase(FD);
8211 }
Richard Smith938f40b2011-06-11 17:19:42 +00008212}
8213
Richard Smith185be182013-04-10 05:48:59 +00008214namespace {
8215/// Information on inheriting constructors to declare.
8216class InheritingConstructorInfo {
8217public:
8218 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8219 : SemaRef(SemaRef), Derived(Derived) {
8220 // Mark the constructors that we already have in the derived class.
8221 //
8222 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8223 // unless there is a user-declared constructor with the same signature in
8224 // the class where the using-declaration appears.
8225 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8226 }
8227
8228 void inheritAll(CXXRecordDecl *RD) {
8229 visitAll(RD, &InheritingConstructorInfo::inherit);
8230 }
8231
8232private:
8233 /// Information about an inheriting constructor.
8234 struct InheritingConstructor {
8235 InheritingConstructor()
8236 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8237
8238 /// If \c true, a constructor with this signature is already declared
8239 /// in the derived class.
8240 bool DeclaredInDerived;
8241
8242 /// The constructor which is inherited.
8243 const CXXConstructorDecl *BaseCtor;
8244
8245 /// The derived constructor we declared.
8246 CXXConstructorDecl *DerivedCtor;
8247 };
8248
8249 /// Inheriting constructors with a given canonical type. There can be at
8250 /// most one such non-template constructor, and any number of templated
8251 /// constructors.
8252 struct InheritingConstructorsForType {
8253 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008254 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8255 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008256
8257 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8258 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8259 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8260 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8261 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8262 false, S.TPL_TemplateMatch))
8263 return Templates[I].second;
8264 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8265 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008266 }
Richard Smith185be182013-04-10 05:48:59 +00008267
8268 return NonTemplate;
8269 }
8270 };
8271
8272 /// Get or create the inheriting constructor record for a constructor.
8273 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8274 QualType CtorType) {
8275 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8276 .getEntry(SemaRef, Ctor);
8277 }
8278
8279 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8280
8281 /// Process all constructors for a class.
8282 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8283 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8284 CtorE = RD->ctor_end();
8285 CtorIt != CtorE; ++CtorIt)
8286 (this->*Callback)(*CtorIt);
8287 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8288 I(RD->decls_begin()), E(RD->decls_end());
8289 I != E; ++I) {
8290 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8291 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8292 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008293 }
8294 }
Richard Smith185be182013-04-10 05:48:59 +00008295
8296 /// Note that a constructor (or constructor template) was declared in Derived.
8297 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8298 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8299 }
8300
8301 /// Inherit a single constructor.
8302 void inherit(const CXXConstructorDecl *Ctor) {
8303 const FunctionProtoType *CtorType =
8304 Ctor->getType()->castAs<FunctionProtoType>();
8305 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8306 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8307
8308 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8309
8310 // Core issue (no number yet): the ellipsis is always discarded.
8311 if (EPI.Variadic) {
8312 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8313 SemaRef.Diag(Ctor->getLocation(),
8314 diag::note_using_decl_constructor_ellipsis);
8315 EPI.Variadic = false;
8316 }
8317
8318 // Declare a constructor for each number of parameters.
8319 //
8320 // C++11 [class.inhctor]p1:
8321 // The candidate set of inherited constructors from the class X named in
8322 // the using-declaration consists of [... modulo defects ...] for each
8323 // constructor or constructor template of X, the set of constructors or
8324 // constructor templates that results from omitting any ellipsis parameter
8325 // specification and successively omitting parameters with a default
8326 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008327 unsigned MinParams = minParamsToInherit(Ctor);
8328 unsigned Params = Ctor->getNumParams();
8329 if (Params >= MinParams) {
8330 do
8331 declareCtor(UsingLoc, Ctor,
8332 SemaRef.Context.getFunctionType(
8333 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8334 while (Params > MinParams &&
8335 Ctor->getParamDecl(--Params)->hasDefaultArg());
8336 }
Richard Smith185be182013-04-10 05:48:59 +00008337 }
8338
8339 /// Find the using-declaration which specified that we should inherit the
8340 /// constructors of \p Base.
8341 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8342 // No fancy lookup required; just look for the base constructor name
8343 // directly within the derived class.
8344 ASTContext &Context = SemaRef.Context;
8345 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8346 Context.getCanonicalType(Context.getRecordType(Base)));
8347 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8348 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8349 }
8350
8351 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8352 // C++11 [class.inhctor]p3:
8353 // [F]or each constructor template in the candidate set of inherited
8354 // constructors, a constructor template is implicitly declared
8355 if (Ctor->getDescribedFunctionTemplate())
8356 return 0;
8357
8358 // For each non-template constructor in the candidate set of inherited
8359 // constructors other than a constructor having no parameters or a
8360 // copy/move constructor having a single parameter, a constructor is
8361 // implicitly declared [...]
8362 if (Ctor->getNumParams() == 0)
8363 return 1;
8364 if (Ctor->isCopyOrMoveConstructor())
8365 return 2;
8366
8367 // Per discussion on core reflector, never inherit a constructor which
8368 // would become a default, copy, or move constructor of Derived either.
8369 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8370 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8371 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8372 }
8373
8374 /// Declare a single inheriting constructor, inheriting the specified
8375 /// constructor, with the given type.
8376 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8377 QualType DerivedType) {
8378 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8379
8380 // C++11 [class.inhctor]p3:
8381 // ... a constructor is implicitly declared with the same constructor
8382 // characteristics unless there is a user-declared constructor with
8383 // the same signature in the class where the using-declaration appears
8384 if (Entry.DeclaredInDerived)
8385 return;
8386
8387 // C++11 [class.inhctor]p7:
8388 // If two using-declarations declare inheriting constructors with the
8389 // same signature, the program is ill-formed
8390 if (Entry.DerivedCtor) {
8391 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8392 // Only diagnose this once per constructor.
8393 if (Entry.DerivedCtor->isInvalidDecl())
8394 return;
8395 Entry.DerivedCtor->setInvalidDecl();
8396
8397 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8398 SemaRef.Diag(BaseCtor->getLocation(),
8399 diag::note_using_decl_constructor_conflict_current_ctor);
8400 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8401 diag::note_using_decl_constructor_conflict_previous_ctor);
8402 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8403 diag::note_using_decl_constructor_conflict_previous_using);
8404 } else {
8405 // Core issue (no number): if the same inheriting constructor is
8406 // produced by multiple base class constructors from the same base
8407 // class, the inheriting constructor is defined as deleted.
8408 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8409 }
8410
8411 return;
8412 }
8413
8414 ASTContext &Context = SemaRef.Context;
8415 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8416 Context.getCanonicalType(Context.getRecordType(Derived)));
8417 DeclarationNameInfo NameInfo(Name, UsingLoc);
8418
8419 TemplateParameterList *TemplateParams = 0;
8420 if (const FunctionTemplateDecl *FTD =
8421 BaseCtor->getDescribedFunctionTemplate()) {
8422 TemplateParams = FTD->getTemplateParameters();
8423 // We're reusing template parameters from a different DeclContext. This
8424 // is questionable at best, but works out because the template depth in
8425 // both places is guaranteed to be 0.
8426 // FIXME: Rebuild the template parameters in the new context, and
8427 // transform the function type to refer to them.
8428 }
8429
8430 // Build type source info pointing at the using-declaration. This is
8431 // required by template instantiation.
8432 TypeSourceInfo *TInfo =
8433 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8434 FunctionProtoTypeLoc ProtoLoc =
8435 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8436
8437 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8438 Context, Derived, UsingLoc, NameInfo, DerivedType,
8439 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8440 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8441
8442 // Build an unevaluated exception specification for this constructor.
8443 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8444 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8445 EPI.ExceptionSpecType = EST_Unevaluated;
8446 EPI.ExceptionSpecDecl = DerivedCtor;
8447 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8448 FPT->getArgTypes(), EPI));
8449
8450 // Build the parameter declarations.
8451 SmallVector<ParmVarDecl *, 16> ParamDecls;
8452 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8453 TypeSourceInfo *TInfo =
8454 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8455 ParmVarDecl *PD = ParmVarDecl::Create(
8456 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8457 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8458 PD->setScopeInfo(0, I);
8459 PD->setImplicit();
8460 ParamDecls.push_back(PD);
8461 ProtoLoc.setArg(I, PD);
8462 }
8463
8464 // Set up the new constructor.
8465 DerivedCtor->setAccess(BaseCtor->getAccess());
8466 DerivedCtor->setParams(ParamDecls);
8467 DerivedCtor->setInheritedConstructor(BaseCtor);
8468 if (BaseCtor->isDeleted())
8469 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8470
8471 // If this is a constructor template, build the template declaration.
8472 if (TemplateParams) {
8473 FunctionTemplateDecl *DerivedTemplate =
8474 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8475 TemplateParams, DerivedCtor);
8476 DerivedTemplate->setAccess(BaseCtor->getAccess());
8477 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8478 Derived->addDecl(DerivedTemplate);
8479 } else {
8480 Derived->addDecl(DerivedCtor);
8481 }
8482
8483 Entry.BaseCtor = BaseCtor;
8484 Entry.DerivedCtor = DerivedCtor;
8485 }
8486
8487 Sema &SemaRef;
8488 CXXRecordDecl *Derived;
8489 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8490 MapType Map;
8491};
8492}
8493
8494void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8495 // Defer declaring the inheriting constructors until the class is
8496 // instantiated.
8497 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008498 return;
8499
Richard Smith185be182013-04-10 05:48:59 +00008500 // Find base classes from which we might inherit constructors.
8501 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8502 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8503 BaseE = ClassDecl->bases_end();
8504 BaseIt != BaseE; ++BaseIt)
8505 if (BaseIt->getInheritConstructors())
8506 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008507
Richard Smith185be182013-04-10 05:48:59 +00008508 // Go no further if we're not inheriting any constructors.
8509 if (InheritedBases.empty())
8510 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008511
Richard Smith185be182013-04-10 05:48:59 +00008512 // Declare the inherited constructors.
8513 InheritingConstructorInfo ICI(*this, ClassDecl);
8514 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8515 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008516}
8517
Richard Smithc2bc61b2013-03-18 21:12:30 +00008518void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8519 CXXConstructorDecl *Constructor) {
8520 CXXRecordDecl *ClassDecl = Constructor->getParent();
8521 assert(Constructor->getInheritedConstructor() &&
8522 !Constructor->doesThisDeclarationHaveABody() &&
8523 !Constructor->isDeleted());
8524
8525 SynthesizedFunctionScope Scope(*this, Constructor);
8526 DiagnosticErrorTrap Trap(Diags);
8527 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8528 Trap.hasErrorOccurred()) {
8529 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8530 << Context.getTagDeclType(ClassDecl);
8531 Constructor->setInvalidDecl();
8532 return;
8533 }
8534
8535 SourceLocation Loc = Constructor->getLocation();
8536 Constructor->setBody(new (Context) CompoundStmt(Loc));
8537
Eli Friedman276dd182013-09-05 00:02:25 +00008538 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008539 MarkVTableUsed(CurrentLocation, ClassDecl);
8540
8541 if (ASTMutationListener *L = getASTMutationListener()) {
8542 L->CompletedImplicitDefinition(Constructor);
8543 }
8544}
8545
8546
Alexis Huntf91729462011-05-12 22:46:25 +00008547Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008548Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8549 CXXRecordDecl *ClassDecl = MD->getParent();
8550
Douglas Gregorf1203042010-07-01 19:09:28 +00008551 // C++ [except.spec]p14:
8552 // An implicitly declared special member function (Clause 12) shall have
8553 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008554 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008555 if (ClassDecl->isInvalidDecl())
8556 return ExceptSpec;
8557
Douglas Gregorf1203042010-07-01 19:09:28 +00008558 // Direct base-class destructors.
8559 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8560 BEnd = ClassDecl->bases_end();
8561 B != BEnd; ++B) {
8562 if (B->isVirtual()) // Handled below.
8563 continue;
8564
8565 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008566 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008567 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008568 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008569
Douglas Gregorf1203042010-07-01 19:09:28 +00008570 // Virtual base-class destructors.
8571 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8572 BEnd = ClassDecl->vbases_end();
8573 B != BEnd; ++B) {
8574 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008575 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008576 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008577 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008578
Douglas Gregorf1203042010-07-01 19:09:28 +00008579 // Field destructors.
8580 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8581 FEnd = ClassDecl->field_end();
8582 F != FEnd; ++F) {
8583 if (const RecordType *RecordTy
8584 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008585 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008586 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008587 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008588
Alexis Huntf91729462011-05-12 22:46:25 +00008589 return ExceptSpec;
8590}
8591
8592CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8593 // C++ [class.dtor]p2:
8594 // If a class has no user-declared destructor, a destructor is
8595 // declared implicitly. An implicitly-declared destructor is an
8596 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008597 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008598
Richard Smith8bf22e52012-11-29 01:34:07 +00008599 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8600 if (DSM.isAlreadyBeingDeclared())
8601 return 0;
8602
Douglas Gregor7454c562010-07-02 20:37:36 +00008603 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008604 CanQualType ClassType
8605 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008606 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008607 DeclarationName Name
8608 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008609 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008610 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008611 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8612 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008613 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008614 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008615 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008616 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008617
8618 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008619 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008620 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008621
Richard Smith6b02d462012-12-08 08:32:28 +00008622 AddOverriddenMethods(ClassDecl, Destructor);
8623
8624 // We don't need to use SpecialMemberIsTrivial here; triviality for
8625 // destructors is easy to compute.
8626 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8627
8628 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008629 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008630
Douglas Gregor7454c562010-07-02 20:37:36 +00008631 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008632 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008633
Douglas Gregor7454c562010-07-02 20:37:36 +00008634 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008635 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008636 PushOnScopeChains(Destructor, S, false);
8637 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008638
Douglas Gregorf1203042010-07-01 19:09:28 +00008639 return Destructor;
8640}
8641
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008642void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008643 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008644 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008645 !Destructor->doesThisDeclarationHaveABody() &&
8646 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008647 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008648 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008649 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008650
Douglas Gregor54818f02010-05-12 16:39:35 +00008651 if (Destructor->isInvalidDecl())
8652 return;
8653
Eli Friedmaneaf34142012-10-18 20:14:08 +00008654 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008655
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008656 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008657 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8658 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008659
Douglas Gregor54818f02010-05-12 16:39:35 +00008660 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008661 Diag(CurrentLocation, diag::note_member_synthesized_at)
8662 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8663
8664 Destructor->setInvalidDecl();
8665 return;
8666 }
8667
Douglas Gregor73193272010-09-20 16:48:21 +00008668 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008669 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008670 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008671 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008672
8673 if (ASTMutationListener *L = getASTMutationListener()) {
8674 L->CompletedImplicitDefinition(Destructor);
8675 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008676}
8677
Richard Smith84973e52012-04-21 18:42:51 +00008678/// \brief Perform any semantic analysis which needs to be delayed until all
8679/// pending class member declarations have been parsed.
8680void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008681 // If the context is an invalid C++ class, just suppress these checks.
8682 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8683 if (Record->isInvalidDecl()) {
8684 DelayedDestructorExceptionSpecChecks.clear();
8685 return;
8686 }
8687 }
8688
Richard Smith84973e52012-04-21 18:42:51 +00008689 // Perform any deferred checking of exception specifications for virtual
8690 // destructors.
8691 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8692 i != e; ++i) {
8693 const CXXDestructorDecl *Dtor =
8694 DelayedDestructorExceptionSpecChecks[i].first;
8695 assert(!Dtor->getParent()->isDependentType() &&
8696 "Should not ever add destructors of templates into the list.");
8697 CheckOverridingFunctionExceptionSpec(Dtor,
8698 DelayedDestructorExceptionSpecChecks[i].second);
8699 }
8700 DelayedDestructorExceptionSpecChecks.clear();
8701}
8702
Richard Smithd3b5c9082012-07-27 04:22:15 +00008703void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8704 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008705 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008706 "adjusting dtor exception specs was introduced in c++11");
8707
Sebastian Redl623ea822011-05-19 05:13:44 +00008708 // C++11 [class.dtor]p3:
8709 // A declaration of a destructor that does not have an exception-
8710 // specification is implicitly considered to have the same exception-
8711 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008712 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008713 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008714 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008715 return;
8716
Chandler Carruth9a797572011-09-20 04:55:26 +00008717 // Replace the destructor's type, building off the existing one. Fortunately,
8718 // the only thing of interest in the destructor type is its extended info.
8719 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008720 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8721 EPI.ExceptionSpecType = EST_Unevaluated;
8722 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008723 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008724
Sebastian Redl623ea822011-05-19 05:13:44 +00008725 // FIXME: If the destructor has a body that could throw, and the newly created
8726 // spec doesn't allow exceptions, we should emit a warning, because this
8727 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008728 // However, we don't have a body or an exception specification yet, so it
8729 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008730}
8731
Pavel Labath58934982013-08-30 08:52:28 +00008732namespace {
8733/// \brief An abstract base class for all helper classes used in building the
8734// copy/move operators. These classes serve as factory functions and help us
8735// avoid using the same Expr* in the AST twice.
8736class ExprBuilder {
8737 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8738 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8739
8740protected:
8741 static Expr *assertNotNull(Expr *E) {
8742 assert(E && "Expression construction must not fail.");
8743 return E;
8744 }
8745
8746public:
8747 ExprBuilder() {}
8748 virtual ~ExprBuilder() {}
8749
8750 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8751};
8752
8753class RefBuilder: public ExprBuilder {
8754 VarDecl *Var;
8755 QualType VarType;
8756
8757public:
8758 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8759 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8760 }
8761
8762 RefBuilder(VarDecl *Var, QualType VarType)
8763 : Var(Var), VarType(VarType) {}
8764};
8765
8766class ThisBuilder: public ExprBuilder {
8767public:
8768 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8769 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8770 }
8771};
8772
8773class CastBuilder: public ExprBuilder {
8774 const ExprBuilder &Builder;
8775 QualType Type;
8776 ExprValueKind Kind;
8777 const CXXCastPath &Path;
8778
8779public:
8780 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8781 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8782 CK_UncheckedDerivedToBase, Kind,
8783 &Path).take());
8784 }
8785
8786 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8787 const CXXCastPath &Path)
8788 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8789};
8790
8791class DerefBuilder: public ExprBuilder {
8792 const ExprBuilder &Builder;
8793
8794public:
8795 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8796 return assertNotNull(
8797 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8798 }
8799
8800 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8801};
8802
8803class MemberBuilder: public ExprBuilder {
8804 const ExprBuilder &Builder;
8805 QualType Type;
8806 CXXScopeSpec SS;
8807 bool IsArrow;
8808 LookupResult &MemberLookup;
8809
8810public:
8811 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8812 return assertNotNull(S.BuildMemberReferenceExpr(
8813 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8814 MemberLookup, 0).take());
8815 }
8816
8817 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8818 LookupResult &MemberLookup)
8819 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8820 MemberLookup(MemberLookup) {}
8821};
8822
8823class MoveCastBuilder: public ExprBuilder {
8824 const ExprBuilder &Builder;
8825
8826public:
8827 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8828 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8829 }
8830
8831 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8832};
8833
8834class LvalueConvBuilder: public ExprBuilder {
8835 const ExprBuilder &Builder;
8836
8837public:
8838 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8839 return assertNotNull(
8840 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8841 }
8842
8843 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8844};
8845
8846class SubscriptBuilder: public ExprBuilder {
8847 const ExprBuilder &Base;
8848 const ExprBuilder &Index;
8849
8850public:
8851 virtual Expr *build(Sema &S, SourceLocation Loc) const
8852 LLVM_OVERRIDE {
8853 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8854 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8855 }
8856
8857 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8858 : Base(Base), Index(Index) {}
8859};
8860
8861} // end anonymous namespace
8862
Richard Smith41ae3282012-11-14 00:50:40 +00008863/// When generating a defaulted copy or move assignment operator, if a field
8864/// should be copied with __builtin_memcpy rather than via explicit assignments,
8865/// do so. This optimization only applies for arrays of scalars, and for arrays
8866/// of class type where the selected copy/move-assignment operator is trivial.
8867static StmtResult
8868buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008869 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008870 // Compute the size of the memory buffer to be copied.
8871 QualType SizeType = S.Context.getSizeType();
8872 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8873 S.Context.getTypeSizeInChars(T).getQuantity());
8874
8875 // Take the address of the field references for "from" and "to". We
8876 // directly construct UnaryOperators here because semantic analysis
8877 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008878 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008879 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8880 S.Context.getPointerType(From->getType()),
8881 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008882 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008883 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8884 S.Context.getPointerType(To->getType()),
8885 VK_RValue, OK_Ordinary, Loc);
8886
8887 const Type *E = T->getBaseElementTypeUnsafe();
8888 bool NeedsCollectableMemCpy =
8889 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8890
8891 // Create a reference to the __builtin_objc_memmove_collectable function
8892 StringRef MemCpyName = NeedsCollectableMemCpy ?
8893 "__builtin_objc_memmove_collectable" :
8894 "__builtin_memcpy";
8895 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8896 Sema::LookupOrdinaryName);
8897 S.LookupName(R, S.TUScope, true);
8898
8899 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8900 if (!MemCpy)
8901 // Something went horribly wrong earlier, and we will have complained
8902 // about it.
8903 return StmtError();
8904
8905 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8906 VK_RValue, Loc, 0);
8907 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8908
8909 Expr *CallArgs[] = {
8910 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8911 };
8912 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8913 Loc, CallArgs, Loc);
8914
8915 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8916 return S.Owned(Call.takeAs<Stmt>());
8917}
8918
Sebastian Redl22653ba2011-08-30 19:58:05 +00008919/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008920/// \c To.
8921///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008922/// This routine is used to copy/move the members of a class with an
8923/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008924/// copied are arrays, this routine builds for loops to copy them.
8925///
8926/// \param S The Sema object used for type-checking.
8927///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008928/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008929///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008930/// \param T The type of the expressions being copied/moved. Both expressions
8931/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008932///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008933/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008934///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008935/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008936///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008937/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008938/// Otherwise, it's a non-static member subobject.
8939///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008940/// \param Copying Whether we're copying or moving.
8941///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008942/// \param Depth Internal parameter recording the depth of the recursion.
8943///
Richard Smith41ae3282012-11-14 00:50:40 +00008944/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8945/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00008946static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00008947buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008948 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00008949 bool CopyingBaseSubobject, bool Copying,
8950 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00008951 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00008952 // Each subobject is assigned in the manner appropriate to its type:
8953 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00008954 // - if the subobject is of class type, as if by a call to operator= with
8955 // the subobject as the object expression and the corresponding
8956 // subobject of x as a single function argument (as if by explicit
8957 // qualification; that is, ignoring any possible virtual overriding
8958 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00008959 //
8960 // C++03 [class.copy]p13:
8961 // - if the subobject is of class type, the copy assignment operator for
8962 // the class is used (as if by explicit qualification; that is,
8963 // ignoring any possible virtual overriding functions in more derived
8964 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008965 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8966 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00008967
Douglas Gregorb139cd52010-05-01 20:49:11 +00008968 // Look for operator=.
8969 DeclarationName Name
8970 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8971 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8972 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008973
Richard Smith52c0b582012-11-13 00:54:12 +00008974 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8975 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008976 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00008977 LookupResult::Filter F = OpLookup.makeFilter();
8978 while (F.hasNext()) {
8979 NamedDecl *D = F.next();
8980 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8981 if (Method->isCopyAssignmentOperator() ||
8982 (!Copying && Method->isMoveAssignmentOperator()))
8983 continue;
8984
8985 F.erase();
8986 }
8987 F.done();
John McCallab8c2732010-03-16 06:11:48 +00008988 }
Richard Smith52c0b582012-11-13 00:54:12 +00008989
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008990 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00008991 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008992 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00008993 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008994 // ambiguities), we need to cast "this" to that subobject type; to
8995 // ensure that we don't go through the virtual call mechanism, we need
8996 // to qualify the operator= name with the base class (see below). However,
8997 // this means that if the base class has a protected copy assignment
8998 // operator, the protected member access check will fail. So, we
8999 // rewrite "protected" access to "public" access in this case, since we
9000 // know by construction that we're calling from a derived class.
9001 if (CopyingBaseSubobject) {
9002 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9003 L != LEnd; ++L) {
9004 if (L.getAccess() == AS_protected)
9005 L.setAccess(AS_public);
9006 }
9007 }
Richard Smith52c0b582012-11-13 00:54:12 +00009008
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 // Create the nested-name-specifier that will be used to qualify the
9010 // reference to operator=; this is required to suppress the virtual
9011 // call mechanism.
9012 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009013 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009014 SS.MakeTrivial(S.Context,
9015 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009016 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009017 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009018
Douglas Gregorb139cd52010-05-01 20:49:11 +00009019 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009020 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009021 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9022 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009023 /*FirstQualifierInScope=*/0,
9024 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009025 /*TemplateArgs=*/0,
9026 /*SuppressQualifierCheck=*/true);
9027 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009028 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009029
Douglas Gregorb139cd52010-05-01 20:49:11 +00009030 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009031
Pavel Labath58934982013-08-30 08:52:28 +00009032 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009033 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009034 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009035 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009036 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009037 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009038
Richard Smith41ae3282012-11-14 00:50:40 +00009039 // If we built a call to a trivial 'operator=' while copying an array,
9040 // bail out. We'll replace the whole shebang with a memcpy.
9041 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9042 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9043 return StmtResult((Stmt*)0);
9044
Richard Smith52c0b582012-11-13 00:54:12 +00009045 // Convert to an expression-statement, and clean up any produced
9046 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009047 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009048 }
John McCallab8c2732010-03-16 06:11:48 +00009049
Richard Smith52c0b582012-11-13 00:54:12 +00009050 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009051 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009052 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009053 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009054 ExprResult Assignment = S.CreateBuiltinBinOp(
9055 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009056 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009057 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009058 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009059 }
Richard Smith52c0b582012-11-13 00:54:12 +00009060
9061 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009062 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009063
Douglas Gregorb139cd52010-05-01 20:49:11 +00009064 // Construct a loop over the array bounds, e.g.,
9065 //
9066 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9067 //
9068 // that will copy each of the array elements.
9069 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009070
Douglas Gregorb139cd52010-05-01 20:49:11 +00009071 // Create the iteration variable.
9072 IdentifierInfo *IterationVarName = 0;
9073 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009074 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009075 llvm::raw_svector_ostream OS(Str);
9076 OS << "__i" << Depth;
9077 IterationVarName = &S.Context.Idents.get(OS.str());
9078 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009079 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009080 IterationVarName, SizeType,
9081 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009082 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009083
Douglas Gregorb139cd52010-05-01 20:49:11 +00009084 // Initialize the iteration variable to zero.
9085 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009086 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009087
Pavel Labath58934982013-08-30 08:52:28 +00009088 // Creates a reference to the iteration variable.
9089 RefBuilder IterationVarRef(IterationVar, SizeType);
9090 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009091
Douglas Gregorb139cd52010-05-01 20:49:11 +00009092 // Create the DeclStmt that holds the iteration variable.
9093 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009094
Douglas Gregorb139cd52010-05-01 20:49:11 +00009095 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009096 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9097 MoveCastBuilder FromIndexMove(FromIndexCopy);
9098 const ExprBuilder *FromIndex;
9099 if (Copying)
9100 FromIndex = &FromIndexCopy;
9101 else
9102 FromIndex = &FromIndexMove;
9103
9104 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009105
9106 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009107 StmtResult Copy =
9108 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009109 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009110 Copying, Depth + 1);
9111 // Bail out if copying fails or if we determined that we should use memcpy.
9112 if (Copy.isInvalid() || !Copy.get())
9113 return Copy;
9114
9115 // Create the comparison against the array bound.
9116 llvm::APInt Upper
9117 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9118 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009119 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009120 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9121 BO_NE, S.Context.BoolTy,
9122 VK_RValue, OK_Ordinary, Loc, false);
9123
9124 // Create the pre-increment of the iteration variable.
9125 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009126 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9127 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009128
Douglas Gregorb139cd52010-05-01 20:49:11 +00009129 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009130 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009132 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009133 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009134}
9135
Richard Smith41ae3282012-11-14 00:50:40 +00009136static StmtResult
9137buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009138 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009139 bool CopyingBaseSubobject, bool Copying) {
9140 // Maybe we should use a memcpy?
9141 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9142 T.isTriviallyCopyableType(S.Context))
9143 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9144
9145 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9146 CopyingBaseSubobject,
9147 Copying, 0));
9148
9149 // If we ended up picking a trivial assignment operator for an array of a
9150 // non-trivially-copyable class type, just emit a memcpy.
9151 if (!Result.isInvalid() && !Result.get())
9152 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9153
9154 return Result;
9155}
9156
Richard Smithd3b5c9082012-07-27 04:22:15 +00009157Sema::ImplicitExceptionSpecification
9158Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9159 CXXRecordDecl *ClassDecl = MD->getParent();
9160
9161 ImplicitExceptionSpecification ExceptSpec(*this);
9162 if (ClassDecl->isInvalidDecl())
9163 return ExceptSpec;
9164
9165 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9166 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9167 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9168
Douglas Gregor68e11362010-07-01 17:48:08 +00009169 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009170 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009171 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009172
9173 // It is unspecified whether or not an implicit copy assignment operator
9174 // attempts to deduplicate calls to assignment operators of virtual bases are
9175 // made. As such, this exception specification is effectively unspecified.
9176 // Based on a similar decision made for constness in C++0x, we're erring on
9177 // the side of assuming such calls to be made regardless of whether they
9178 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00009179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9180 BaseEnd = ClassDecl->bases_end();
9181 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009182 if (Base->isVirtual())
9183 continue;
9184
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009185 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00009186 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009187 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9188 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009189 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009190 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009191
9192 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9193 BaseEnd = ClassDecl->vbases_end();
9194 Base != BaseEnd; ++Base) {
9195 CXXRecordDecl *BaseClassDecl
9196 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9197 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9198 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009199 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009200 }
9201
Douglas Gregor68e11362010-07-01 17:48:08 +00009202 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9203 FieldEnd = ClassDecl->field_end();
9204 Field != FieldEnd;
9205 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009206 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009207 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9208 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009209 LookupCopyingAssignment(FieldClassDecl,
9210 ArgQuals | FieldType.getCVRQualifiers(),
9211 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009212 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009213 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009214 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009215
Richard Smithd3b5c9082012-07-27 04:22:15 +00009216 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009217}
9218
9219CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9220 // Note: The following rules are largely analoguous to the copy
9221 // constructor rules. Note that virtual bases are not taken into account
9222 // for determining the argument type of the operator. Note also that
9223 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009224 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009225
Richard Smith8bf22e52012-11-29 01:34:07 +00009226 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9227 if (DSM.isAlreadyBeingDeclared())
9228 return 0;
9229
Alexis Hunt119f3652011-05-14 05:23:20 +00009230 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9231 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009232 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9233 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009234 ArgType = ArgType.withConst();
9235 ArgType = Context.getLValueReferenceType(ArgType);
9236
Richard Smith99005e62013-05-07 03:19:20 +00009237 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9238 CXXCopyAssignment,
9239 Const);
9240
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009241 // An implicitly-declared copy assignment operator is an inline public
9242 // member of its class.
9243 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009244 SourceLocation ClassLoc = ClassDecl->getLocation();
9245 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009246 CXXMethodDecl *CopyAssignment =
9247 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9248 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9249 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009250 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009251 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009252 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009253
9254 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009255 FunctionProtoType::ExtProtoInfo EPI =
9256 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009257 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009258
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009259 // Add the parameter to the operator.
9260 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009261 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009262 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009263 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009264 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009265
Richard Smith6b02d462012-12-08 08:32:28 +00009266 AddOverriddenMethods(ClassDecl, CopyAssignment);
9267
9268 CopyAssignment->setTrivial(
9269 ClassDecl->needsOverloadResolutionForCopyAssignment()
9270 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9271 : ClassDecl->hasTrivialCopyAssignment());
9272
Richard Smith99005e62013-05-07 03:19:20 +00009273 // C++11 [class.copy]p19:
Nico Weber94e746d2012-01-23 03:19:29 +00009274 // .... If the class definition does not explicitly declare a copy
9275 // assignment operator, there is no user-declared move constructor, and
9276 // there is no user-declared move assignment operator, a copy assignment
9277 // operator is implicitly declared as defaulted.
Richard Smith852265f2012-03-30 20:53:28 +00009278 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009279 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009280
Richard Smith6b02d462012-12-08 08:32:28 +00009281 // Note that we have added this copy-assignment operator.
9282 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9283
9284 if (Scope *S = getScopeForContext(ClassDecl))
9285 PushOnScopeChains(CopyAssignment, S, false);
9286 ClassDecl->addDecl(CopyAssignment);
9287
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009288 return CopyAssignment;
9289}
9290
Richard Smithd577fbb2013-06-13 03:23:42 +00009291/// Diagnose an implicit copy operation for a class which is odr-used, but
9292/// which is deprecated because the class has a user-declared copy constructor,
9293/// copy assignment operator, or destructor.
9294static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9295 SourceLocation UseLoc) {
9296 assert(CopyOp->isImplicit());
9297
9298 CXXRecordDecl *RD = CopyOp->getParent();
9299 CXXMethodDecl *UserDeclaredOperation = 0;
9300
9301 // In Microsoft mode, assignment operations don't affect constructors and
9302 // vice versa.
9303 if (RD->hasUserDeclaredDestructor()) {
9304 UserDeclaredOperation = RD->getDestructor();
9305 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9306 RD->hasUserDeclaredCopyConstructor() &&
9307 !S.getLangOpts().MicrosoftMode) {
9308 // Find any user-declared copy constructor.
9309 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9310 E = RD->ctor_end(); I != E; ++I) {
9311 if (I->isCopyConstructor()) {
9312 UserDeclaredOperation = *I;
9313 break;
9314 }
9315 }
9316 assert(UserDeclaredOperation);
9317 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9318 RD->hasUserDeclaredCopyAssignment() &&
9319 !S.getLangOpts().MicrosoftMode) {
9320 // Find any user-declared move assignment operator.
9321 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9322 E = RD->method_end(); I != E; ++I) {
9323 if (I->isCopyAssignmentOperator()) {
9324 UserDeclaredOperation = *I;
9325 break;
9326 }
9327 }
9328 assert(UserDeclaredOperation);
9329 }
9330
9331 if (UserDeclaredOperation) {
9332 S.Diag(UserDeclaredOperation->getLocation(),
9333 diag::warn_deprecated_copy_operation)
9334 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9335 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9336 S.Diag(UseLoc, diag::note_member_synthesized_at)
9337 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9338 : Sema::CXXCopyAssignment)
9339 << RD;
9340 }
9341}
9342
Douglas Gregorb139cd52010-05-01 20:49:11 +00009343void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9344 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009345 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009346 CopyAssignOperator->isOverloadedOperator() &&
9347 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009348 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9349 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009350 "DefineImplicitCopyAssignment called for wrong function");
9351
9352 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9353
9354 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9355 CopyAssignOperator->setInvalidDecl();
9356 return;
9357 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009358
9359 // C++11 [class.copy]p18:
9360 // The [definition of an implicitly declared copy assignment operator] is
9361 // deprecated if the class has a user-declared copy constructor or a
9362 // user-declared destructor.
9363 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9364 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9365
Eli Friedman276dd182013-09-05 00:02:25 +00009366 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009367
Eli Friedmaneaf34142012-10-18 20:14:08 +00009368 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009369 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009370
9371 // C++0x [class.copy]p30:
9372 // The implicitly-defined or explicitly-defaulted copy assignment operator
9373 // for a non-union class X performs memberwise copy assignment of its
9374 // subobjects. The direct base classes of X are assigned first, in the
9375 // order of their declaration in the base-specifier-list, and then the
9376 // immediate non-static data members of X are assigned, in the order in
9377 // which they were declared in the class definition.
9378
9379 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009380 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009381
9382 // The parameter for the "other" object, which we are copying from.
9383 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9384 Qualifiers OtherQuals = Other->getType().getQualifiers();
9385 QualType OtherRefType = Other->getType();
9386 if (const LValueReferenceType *OtherRef
9387 = OtherRefType->getAs<LValueReferenceType>()) {
9388 OtherRefType = OtherRef->getPointeeType();
9389 OtherQuals = OtherRefType.getQualifiers();
9390 }
9391
9392 // Our location for everything implicitly-generated.
9393 SourceLocation Loc = CopyAssignOperator->getLocation();
9394
Pavel Labath58934982013-08-30 08:52:28 +00009395 // Builds a DeclRefExpr for the "other" object.
9396 RefBuilder OtherRef(Other, OtherRefType);
9397
9398 // Builds the "this" pointer.
9399 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009400
9401 // Assign base classes.
9402 bool Invalid = false;
9403 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9404 E = ClassDecl->bases_end(); Base != E; ++Base) {
9405 // Form the assignment:
9406 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9407 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009408 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009409 Invalid = true;
9410 continue;
9411 }
9412
John McCallcf142162010-08-07 06:22:56 +00009413 CXXCastPath BasePath;
9414 BasePath.push_back(Base);
9415
Douglas Gregorb139cd52010-05-01 20:49:11 +00009416 // Construct the "from" expression, which is an implicit cast to the
9417 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009418 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9419 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009420
9421 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009422 DerefBuilder DerefThis(This);
9423 CastBuilder To(DerefThis,
9424 Context.getCVRQualifiedType(
9425 BaseType, CopyAssignOperator->getTypeQualifiers()),
9426 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009427
9428 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009429 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009430 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009431 /*CopyingBaseSubobject=*/true,
9432 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009433 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009434 Diag(CurrentLocation, diag::note_member_synthesized_at)
9435 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9436 CopyAssignOperator->setInvalidDecl();
9437 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438 }
9439
9440 // Success! Record the copy.
9441 Statements.push_back(Copy.takeAs<Expr>());
9442 }
9443
Douglas Gregorb139cd52010-05-01 20:49:11 +00009444 // Assign non-static members.
9445 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9446 FieldEnd = ClassDecl->field_end();
9447 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009448 if (Field->isUnnamedBitfield())
9449 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009450
9451 if (Field->isInvalidDecl()) {
9452 Invalid = true;
9453 continue;
9454 }
9455
Douglas Gregorb139cd52010-05-01 20:49:11 +00009456 // Check for members of reference type; we can't copy those.
9457 if (Field->getType()->isReferenceType()) {
9458 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9459 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9460 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009461 Diag(CurrentLocation, diag::note_member_synthesized_at)
9462 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009463 Invalid = true;
9464 continue;
9465 }
9466
9467 // Check for members of const-qualified, non-class type.
9468 QualType BaseType = Context.getBaseElementType(Field->getType());
9469 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9470 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9471 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9472 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009473 Diag(CurrentLocation, diag::note_member_synthesized_at)
9474 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009475 Invalid = true;
9476 continue;
9477 }
John McCall1b1a1db2011-06-17 00:18:42 +00009478
9479 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009480 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9481 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009482
9483 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009484 if (FieldType->isIncompleteArrayType()) {
9485 assert(ClassDecl->hasFlexibleArrayMember() &&
9486 "Incomplete array type is not valid");
9487 continue;
9488 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009489
9490 // Build references to the field in the object we're copying from and to.
9491 CXXScopeSpec SS; // Intentionally empty
9492 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9493 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009494 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009495 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009496
9497 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9498
9499 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009500
Douglas Gregorb139cd52010-05-01 20:49:11 +00009501 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009502 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009503 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009504 /*CopyingBaseSubobject=*/false,
9505 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009506 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009507 Diag(CurrentLocation, diag::note_member_synthesized_at)
9508 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9509 CopyAssignOperator->setInvalidDecl();
9510 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009511 }
9512
9513 // Success! Record the copy.
9514 Statements.push_back(Copy.takeAs<Stmt>());
9515 }
9516
9517 if (!Invalid) {
9518 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009519 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009520
John McCalldadc5752010-08-24 06:29:42 +00009521 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009522 if (Return.isInvalid())
9523 Invalid = true;
9524 else {
9525 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009526
9527 if (Trap.hasErrorOccurred()) {
9528 Diag(CurrentLocation, diag::note_member_synthesized_at)
9529 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9530 Invalid = true;
9531 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009532 }
9533 }
9534
9535 if (Invalid) {
9536 CopyAssignOperator->setInvalidDecl();
9537 return;
9538 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009539
9540 StmtResult Body;
9541 {
9542 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009543 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009544 /*isStmtExpr=*/false);
9545 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9546 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009547 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009548
9549 if (ASTMutationListener *L = getASTMutationListener()) {
9550 L->CompletedImplicitDefinition(CopyAssignOperator);
9551 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009552}
9553
Sebastian Redl22653ba2011-08-30 19:58:05 +00009554Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009555Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9556 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009557
Richard Smithd3b5c9082012-07-27 04:22:15 +00009558 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009559 if (ClassDecl->isInvalidDecl())
9560 return ExceptSpec;
9561
9562 // C++0x [except.spec]p14:
9563 // An implicitly declared special member function (Clause 12) shall have an
9564 // exception-specification. [...]
9565
9566 // It is unspecified whether or not an implicit move assignment operator
9567 // attempts to deduplicate calls to assignment operators of virtual bases are
9568 // made. As such, this exception specification is effectively unspecified.
9569 // Based on a similar decision made for constness in C++0x, we're erring on
9570 // the side of assuming such calls to be made regardless of whether they
9571 // actually happen.
9572 // Note that a move constructor is not implicitly declared when there are
9573 // virtual bases, but it can still be user-declared and explicitly defaulted.
9574 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9575 BaseEnd = ClassDecl->bases_end();
9576 Base != BaseEnd; ++Base) {
9577 if (Base->isVirtual())
9578 continue;
9579
9580 CXXRecordDecl *BaseClassDecl
9581 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9582 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009583 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009584 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009585 }
9586
9587 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9588 BaseEnd = ClassDecl->vbases_end();
9589 Base != BaseEnd; ++Base) {
9590 CXXRecordDecl *BaseClassDecl
9591 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9592 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009593 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009594 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009595 }
9596
9597 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9598 FieldEnd = ClassDecl->field_end();
9599 Field != FieldEnd;
9600 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009601 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009602 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009603 if (CXXMethodDecl *MoveAssign =
9604 LookupMovingAssignment(FieldClassDecl,
9605 FieldType.getCVRQualifiers(),
9606 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009607 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009608 }
9609 }
9610
9611 return ExceptSpec;
9612}
9613
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009614/// Determine whether the class type has any direct or indirect virtual base
9615/// classes which have a non-trivial move assignment operator.
9616static bool
9617hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9618 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9619 BaseEnd = ClassDecl->vbases_end();
9620 Base != BaseEnd; ++Base) {
9621 CXXRecordDecl *BaseClass =
9622 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9623
9624 // Try to declare the move assignment. If it would be deleted, then the
9625 // class does not have a non-trivial move assignment.
9626 if (BaseClass->needsImplicitMoveAssignment())
9627 S.DeclareImplicitMoveAssignment(BaseClass);
9628
Richard Smith16488472012-11-16 00:53:38 +00009629 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009630 return true;
9631 }
9632
9633 return false;
9634}
9635
9636/// Determine whether the given type either has a move constructor or is
9637/// trivially copyable.
9638static bool
9639hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9640 Type = S.Context.getBaseElementType(Type);
9641
9642 // FIXME: Technically, non-trivially-copyable non-class types, such as
9643 // reference types, are supposed to return false here, but that appears
9644 // to be a standard defect.
9645 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidis8e502972012-10-10 16:14:06 +00009646 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009647 return true;
9648
9649 if (Type.isTriviallyCopyableType(S.Context))
9650 return true;
9651
9652 if (IsConstructor) {
Richard Smith2be35f52012-12-01 02:35:44 +00009653 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9654 // give the right answer.
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009655 if (ClassDecl->needsImplicitMoveConstructor())
9656 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smith2be35f52012-12-01 02:35:44 +00009657 return ClassDecl->hasMoveConstructor();
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009658 }
9659
Richard Smith2be35f52012-12-01 02:35:44 +00009660 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9661 // give the right answer.
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009662 if (ClassDecl->needsImplicitMoveAssignment())
9663 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smith2be35f52012-12-01 02:35:44 +00009664 return ClassDecl->hasMoveAssignment();
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009665}
9666
9667/// Determine whether all non-static data members and direct or virtual bases
9668/// of class \p ClassDecl have either a move operation, or are trivially
9669/// copyable.
9670static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9671 bool IsConstructor) {
9672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9673 BaseEnd = ClassDecl->bases_end();
9674 Base != BaseEnd; ++Base) {
9675 if (Base->isVirtual())
9676 continue;
9677
9678 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9679 return false;
9680 }
9681
9682 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9683 BaseEnd = ClassDecl->vbases_end();
9684 Base != BaseEnd; ++Base) {
9685 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9686 return false;
9687 }
9688
9689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9690 FieldEnd = ClassDecl->field_end();
9691 Field != FieldEnd; ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009692 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009693 return false;
9694 }
9695
9696 return true;
9697}
9698
Sebastian Redl22653ba2011-08-30 19:58:05 +00009699CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009700 // C++11 [class.copy]p20:
9701 // If the definition of a class X does not explicitly declare a move
9702 // assignment operator, one will be implicitly declared as defaulted
9703 // if and only if:
9704 //
9705 // - [first 4 bullets]
9706 assert(ClassDecl->needsImplicitMoveAssignment());
9707
Richard Smith8bf22e52012-11-29 01:34:07 +00009708 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9709 if (DSM.isAlreadyBeingDeclared())
9710 return 0;
9711
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009712 // [Checked after we build the declaration]
9713 // - the move assignment operator would not be implicitly defined as
9714 // deleted,
9715
9716 // [DR1402]:
9717 // - X has no direct or indirect virtual base class with a non-trivial
9718 // move assignment operator, and
9719 // - each of X's non-static data members and direct or virtual base classes
9720 // has a type that either has a move assignment operator or is trivially
9721 // copyable.
9722 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9723 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9724 ClassDecl->setFailedImplicitMoveAssignment();
9725 return 0;
9726 }
9727
Sebastian Redl22653ba2011-08-30 19:58:05 +00009728 // Note: The following rules are largely analoguous to the move
9729 // constructor rules.
9730
Sebastian Redl22653ba2011-08-30 19:58:05 +00009731 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9732 QualType RetType = Context.getLValueReferenceType(ArgType);
9733 ArgType = Context.getRValueReferenceType(ArgType);
9734
Richard Smith99005e62013-05-07 03:19:20 +00009735 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9736 CXXMoveAssignment,
9737 false);
9738
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739 // An implicitly-declared move assignment operator is an inline public
9740 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009741 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9742 SourceLocation ClassLoc = ClassDecl->getLocation();
9743 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009744 CXXMethodDecl *MoveAssignment =
9745 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9746 /*TInfo=*/0, /*StorageClass=*/SC_None,
9747 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009748 MoveAssignment->setAccess(AS_public);
9749 MoveAssignment->setDefaulted();
9750 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009751
Richard Smithd3b5c9082012-07-27 04:22:15 +00009752 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009753 FunctionProtoType::ExtProtoInfo EPI =
9754 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009755 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009756
Sebastian Redl22653ba2011-08-30 19:58:05 +00009757 // Add the parameter to the operator.
9758 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9759 ClassLoc, ClassLoc, /*Id=*/0,
9760 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009761 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009762 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009763
Richard Smith6b02d462012-12-08 08:32:28 +00009764 AddOverriddenMethods(ClassDecl, MoveAssignment);
9765
9766 MoveAssignment->setTrivial(
9767 ClassDecl->needsOverloadResolutionForMoveAssignment()
9768 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9769 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009770
9771 // C++0x [class.copy]p9:
9772 // If the definition of a class X does not explicitly declare a move
9773 // assignment operator, one will be implicitly declared as defaulted if and
9774 // only if:
9775 // [...]
9776 // - the move assignment operator would not be implicitly defined as
9777 // deleted.
Richard Smithd951a1d2012-02-18 02:02:13 +00009778 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009779 // Cache this result so that we don't try to generate this over and over
9780 // on every lookup, leaking memory and wasting time.
9781 ClassDecl->setFailedImplicitMoveAssignment();
9782 return 0;
9783 }
9784
Richard Smith6b02d462012-12-08 08:32:28 +00009785 // Note that we have added this copy-assignment operator.
9786 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9787
Sebastian Redl22653ba2011-08-30 19:58:05 +00009788 if (Scope *S = getScopeForContext(ClassDecl))
9789 PushOnScopeChains(MoveAssignment, S, false);
9790 ClassDecl->addDecl(MoveAssignment);
9791
Sebastian Redl22653ba2011-08-30 19:58:05 +00009792 return MoveAssignment;
9793}
9794
9795void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9796 CXXMethodDecl *MoveAssignOperator) {
9797 assert((MoveAssignOperator->isDefaulted() &&
9798 MoveAssignOperator->isOverloadedOperator() &&
9799 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009800 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9801 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009802 "DefineImplicitMoveAssignment called for wrong function");
9803
9804 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9805
9806 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9807 MoveAssignOperator->setInvalidDecl();
9808 return;
9809 }
9810
Eli Friedman276dd182013-09-05 00:02:25 +00009811 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009812
Eli Friedmaneaf34142012-10-18 20:14:08 +00009813 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009814 DiagnosticErrorTrap Trap(Diags);
9815
9816 // C++0x [class.copy]p28:
9817 // The implicitly-defined or move assignment operator for a non-union class
9818 // X performs memberwise move assignment of its subobjects. The direct base
9819 // classes of X are assigned first, in the order of their declaration in the
9820 // base-specifier-list, and then the immediate non-static data members of X
9821 // are assigned, in the order in which they were declared in the class
9822 // definition.
9823
9824 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009825 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009826
9827 // The parameter for the "other" object, which we are move from.
9828 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9829 QualType OtherRefType = Other->getType()->
9830 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009831 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832 "Bad argument type of defaulted move assignment");
9833
9834 // Our location for everything implicitly-generated.
9835 SourceLocation Loc = MoveAssignOperator->getLocation();
9836
Pavel Labath58934982013-08-30 08:52:28 +00009837 // Builds a reference to the "other" object.
9838 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009840 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009841
Pavel Labath58934982013-08-30 08:52:28 +00009842 // Builds the "this" pointer.
9843 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009844
Sebastian Redl22653ba2011-08-30 19:58:05 +00009845 // Assign base classes.
9846 bool Invalid = false;
9847 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9848 E = ClassDecl->bases_end(); Base != E; ++Base) {
9849 // Form the assignment:
9850 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9851 QualType BaseType = Base->getType().getUnqualifiedType();
9852 if (!BaseType->isRecordType()) {
9853 Invalid = true;
9854 continue;
9855 }
9856
9857 CXXCastPath BasePath;
9858 BasePath.push_back(Base);
9859
9860 // Construct the "from" expression, which is an implicit cast to the
9861 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009862 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009863
9864 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009865 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009866
9867 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009868 CastBuilder To(DerefThis,
9869 Context.getCVRQualifiedType(
9870 BaseType, MoveAssignOperator->getTypeQualifiers()),
9871 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872
9873 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009874 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009875 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009876 /*CopyingBaseSubobject=*/true,
9877 /*Copying=*/false);
9878 if (Move.isInvalid()) {
9879 Diag(CurrentLocation, diag::note_member_synthesized_at)
9880 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9881 MoveAssignOperator->setInvalidDecl();
9882 return;
9883 }
9884
9885 // Success! Record the move.
9886 Statements.push_back(Move.takeAs<Expr>());
9887 }
9888
Sebastian Redl22653ba2011-08-30 19:58:05 +00009889 // Assign non-static members.
9890 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9891 FieldEnd = ClassDecl->field_end();
9892 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009893 if (Field->isUnnamedBitfield())
9894 continue;
9895
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009896 if (Field->isInvalidDecl()) {
9897 Invalid = true;
9898 continue;
9899 }
9900
Sebastian Redl22653ba2011-08-30 19:58:05 +00009901 // Check for members of reference type; we can't move those.
9902 if (Field->getType()->isReferenceType()) {
9903 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9904 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9905 Diag(Field->getLocation(), diag::note_declared_at);
9906 Diag(CurrentLocation, diag::note_member_synthesized_at)
9907 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9908 Invalid = true;
9909 continue;
9910 }
9911
9912 // Check for members of const-qualified, non-class type.
9913 QualType BaseType = Context.getBaseElementType(Field->getType());
9914 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9915 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9916 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9917 Diag(Field->getLocation(), diag::note_declared_at);
9918 Diag(CurrentLocation, diag::note_member_synthesized_at)
9919 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9920 Invalid = true;
9921 continue;
9922 }
9923
9924 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009925 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9926 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009927
9928 QualType FieldType = Field->getType().getNonReferenceType();
9929 if (FieldType->isIncompleteArrayType()) {
9930 assert(ClassDecl->hasFlexibleArrayMember() &&
9931 "Incomplete array type is not valid");
9932 continue;
9933 }
9934
9935 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009936 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9937 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009938 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009939 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009940 MemberBuilder From(MoveOther, OtherRefType,
9941 /*IsArrow=*/false, MemberLookup);
9942 MemberBuilder To(This, getCurrentThisType(),
9943 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009944
Pavel Labath58934982013-08-30 08:52:28 +00009945 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009946 "Member reference with rvalue base must be rvalue except for reference "
9947 "members, which aren't allowed for move assignment.");
9948
Sebastian Redl22653ba2011-08-30 19:58:05 +00009949 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009950 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009951 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009952 /*CopyingBaseSubobject=*/false,
9953 /*Copying=*/false);
9954 if (Move.isInvalid()) {
9955 Diag(CurrentLocation, diag::note_member_synthesized_at)
9956 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9957 MoveAssignOperator->setInvalidDecl();
9958 return;
9959 }
Richard Smith11d19592012-11-12 23:33:00 +00009960
Sebastian Redl22653ba2011-08-30 19:58:05 +00009961 // Success! Record the copy.
9962 Statements.push_back(Move.takeAs<Stmt>());
9963 }
9964
9965 if (!Invalid) {
9966 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009967 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00009968
9969 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9970 if (Return.isInvalid())
9971 Invalid = true;
9972 else {
9973 Statements.push_back(Return.takeAs<Stmt>());
9974
9975 if (Trap.hasErrorOccurred()) {
9976 Diag(CurrentLocation, diag::note_member_synthesized_at)
9977 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9978 Invalid = true;
9979 }
9980 }
9981 }
9982
9983 if (Invalid) {
9984 MoveAssignOperator->setInvalidDecl();
9985 return;
9986 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009987
9988 StmtResult Body;
9989 {
9990 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009991 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009992 /*isStmtExpr=*/false);
9993 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9994 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00009995 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9996
9997 if (ASTMutationListener *L = getASTMutationListener()) {
9998 L->CompletedImplicitDefinition(MoveAssignOperator);
9999 }
10000}
10001
Richard Smithd3b5c9082012-07-27 04:22:15 +000010002Sema::ImplicitExceptionSpecification
10003Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10004 CXXRecordDecl *ClassDecl = MD->getParent();
10005
10006 ImplicitExceptionSpecification ExceptSpec(*this);
10007 if (ClassDecl->isInvalidDecl())
10008 return ExceptSpec;
10009
10010 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10011 assert(T->getNumArgs() >= 1 && "not a copy ctor");
10012 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
10013
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010014 // C++ [except.spec]p14:
10015 // An implicitly declared special member function (Clause 12) shall have an
10016 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010017 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10018 BaseEnd = ClassDecl->bases_end();
10019 Base != BaseEnd;
10020 ++Base) {
10021 // Virtual bases are handled below.
10022 if (Base->isVirtual())
10023 continue;
10024
Douglas Gregora6d69502010-07-02 23:41:54 +000010025 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010026 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010027 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010028 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010029 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010030 }
10031 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10032 BaseEnd = ClassDecl->vbases_end();
10033 Base != BaseEnd;
10034 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010035 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010036 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010037 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010038 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010039 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010040 }
10041 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10042 FieldEnd = ClassDecl->field_end();
10043 Field != FieldEnd;
10044 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010045 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010046 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10047 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010048 LookupCopyingConstructor(FieldClassDecl,
10049 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010050 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010051 }
10052 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010053
Richard Smithd3b5c9082012-07-27 04:22:15 +000010054 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010055}
10056
10057CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10058 CXXRecordDecl *ClassDecl) {
10059 // C++ [class.copy]p4:
10060 // If the class definition does not explicitly declare a copy
10061 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010062 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010063
Richard Smith8bf22e52012-11-29 01:34:07 +000010064 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10065 if (DSM.isAlreadyBeingDeclared())
10066 return 0;
10067
Alexis Hunt913820d2011-05-13 06:10:58 +000010068 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10069 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010070 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010071 if (Const)
10072 ArgType = ArgType.withConst();
10073 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010074
Richard Smithb5800092012-06-10 05:43:50 +000010075 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10076 CXXCopyConstructor,
10077 Const);
10078
Douglas Gregor54be3392010-07-01 17:57:27 +000010079 DeclarationName Name
10080 = Context.DeclarationNames.getCXXConstructorName(
10081 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010082 SourceLocation ClassLoc = ClassDecl->getLocation();
10083 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010084
10085 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010086 // member of its class.
10087 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010088 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010089 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010090 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010091 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010092 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010093
Richard Smithd3b5c9082012-07-27 04:22:15 +000010094 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010095 FunctionProtoType::ExtProtoInfo EPI =
10096 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010097 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010098 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010099
Douglas Gregor54be3392010-07-01 17:57:27 +000010100 // Add the parameter to the constructor.
10101 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010102 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010103 /*IdentifierInfo=*/0,
10104 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010105 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010106 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010107
Richard Smith6b02d462012-12-08 08:32:28 +000010108 CopyConstructor->setTrivial(
10109 ClassDecl->needsOverloadResolutionForCopyConstructor()
10110 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10111 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010112
Nico Weber94e746d2012-01-23 03:19:29 +000010113 // C++11 [class.copy]p8:
10114 // ... If the class definition does not explicitly declare a copy
10115 // constructor, there is no user-declared move constructor, and there is no
10116 // user-declared move assignment operator, a copy constructor is implicitly
10117 // declared as defaulted.
Richard Smith852265f2012-03-30 20:53:28 +000010118 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010119 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010120
Richard Smith6b02d462012-12-08 08:32:28 +000010121 // Note that we have declared this constructor.
10122 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10123
10124 if (Scope *S = getScopeForContext(ClassDecl))
10125 PushOnScopeChains(CopyConstructor, S, false);
10126 ClassDecl->addDecl(CopyConstructor);
10127
Douglas Gregor54be3392010-07-01 17:57:27 +000010128 return CopyConstructor;
10129}
10130
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010131void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010132 CXXConstructorDecl *CopyConstructor) {
10133 assert((CopyConstructor->isDefaulted() &&
10134 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010135 !CopyConstructor->doesThisDeclarationHaveABody() &&
10136 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010137 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010138
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010139 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010140 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010141
Richard Smithd577fbb2013-06-13 03:23:42 +000010142 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010143 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010144 // deprecated if the class has a user-declared copy assignment operator
10145 // or a user-declared destructor.
10146 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10147 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10148
Eli Friedmaneaf34142012-10-18 20:14:08 +000010149 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010150 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010151
David Blaikie3fc2f912013-01-17 05:26:25 +000010152 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010153 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010154 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010155 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010156 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010157 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010158 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010159 CopyConstructor->setBody(ActOnCompoundStmt(
10160 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10161 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010162 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010163
Eli Friedman276dd182013-09-05 00:02:25 +000010164 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010165 if (ASTMutationListener *L = getASTMutationListener()) {
10166 L->CompletedImplicitDefinition(CopyConstructor);
10167 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010168}
10169
Sebastian Redl22653ba2011-08-30 19:58:05 +000010170Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010171Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10172 CXXRecordDecl *ClassDecl = MD->getParent();
10173
Sebastian Redl22653ba2011-08-30 19:58:05 +000010174 // C++ [except.spec]p14:
10175 // An implicitly declared special member function (Clause 12) shall have an
10176 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010177 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010178 if (ClassDecl->isInvalidDecl())
10179 return ExceptSpec;
10180
10181 // Direct base-class constructors.
10182 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10183 BEnd = ClassDecl->bases_end();
10184 B != BEnd; ++B) {
10185 if (B->isVirtual()) // Handled below.
10186 continue;
10187
10188 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10189 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010190 CXXConstructorDecl *Constructor =
10191 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010192 // If this is a deleted function, add it anyway. This might be conformant
10193 // with the standard. This might not. I'm not sure. It might not matter.
10194 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010195 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010196 }
10197 }
10198
10199 // Virtual base-class constructors.
10200 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10201 BEnd = ClassDecl->vbases_end();
10202 B != BEnd; ++B) {
10203 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010205 CXXConstructorDecl *Constructor =
10206 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010207 // If this is a deleted function, add it anyway. This might be conformant
10208 // with the standard. This might not. I'm not sure. It might not matter.
10209 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010210 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010211 }
10212 }
10213
10214 // Field constructors.
10215 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10216 FEnd = ClassDecl->field_end();
10217 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010218 QualType FieldType = Context.getBaseElementType(F->getType());
10219 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10220 CXXConstructorDecl *Constructor =
10221 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010222 // If this is a deleted function, add it anyway. This might be conformant
10223 // with the standard. This might not. I'm not sure. It might not matter.
10224 // In particular, the problem is that this function never gets called. It
10225 // might just be ill-formed because this function attempts to refer to
10226 // a deleted function here.
10227 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010228 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010229 }
10230 }
10231
10232 return ExceptSpec;
10233}
10234
10235CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10236 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010237 // C++11 [class.copy]p9:
10238 // If the definition of a class X does not explicitly declare a move
10239 // constructor, one will be implicitly declared as defaulted if and only if:
10240 //
10241 // - [first 4 bullets]
10242 assert(ClassDecl->needsImplicitMoveConstructor());
10243
Richard Smith8bf22e52012-11-29 01:34:07 +000010244 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10245 if (DSM.isAlreadyBeingDeclared())
10246 return 0;
10247
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010248 // [Checked after we build the declaration]
10249 // - the move assignment operator would not be implicitly defined as
10250 // deleted,
10251
10252 // [DR1402]:
10253 // - each of X's non-static data members and direct or virtual base classes
10254 // has a type that either has a move constructor or is trivially copyable.
10255 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10256 ClassDecl->setFailedImplicitMoveConstructor();
10257 return 0;
10258 }
10259
Sebastian Redl22653ba2011-08-30 19:58:05 +000010260 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10261 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010262
Richard Smithb5800092012-06-10 05:43:50 +000010263 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10264 CXXMoveConstructor,
10265 false);
10266
Sebastian Redl22653ba2011-08-30 19:58:05 +000010267 DeclarationName Name
10268 = Context.DeclarationNames.getCXXConstructorName(
10269 Context.getCanonicalType(ClassType));
10270 SourceLocation ClassLoc = ClassDecl->getLocation();
10271 DeclarationNameInfo NameInfo(Name, ClassLoc);
10272
Richard Smith99005e62013-05-07 03:19:20 +000010273 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010274 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010275 // member of its class.
10276 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010277 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010278 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010279 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010280 MoveConstructor->setAccess(AS_public);
10281 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010282
Richard Smithd3b5c9082012-07-27 04:22:15 +000010283 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010284 FunctionProtoType::ExtProtoInfo EPI =
10285 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010286 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010287 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010288
Sebastian Redl22653ba2011-08-30 19:58:05 +000010289 // Add the parameter to the constructor.
10290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10291 ClassLoc, ClassLoc,
10292 /*IdentifierInfo=*/0,
10293 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010295 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010296
Richard Smith6b02d462012-12-08 08:32:28 +000010297 MoveConstructor->setTrivial(
10298 ClassDecl->needsOverloadResolutionForMoveConstructor()
10299 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10300 : ClassDecl->hasTrivialMoveConstructor());
10301
Sebastian Redl22653ba2011-08-30 19:58:05 +000010302 // C++0x [class.copy]p9:
10303 // If the definition of a class X does not explicitly declare a move
10304 // constructor, one will be implicitly declared as defaulted if and only if:
10305 // [...]
10306 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010307 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010308 // Cache this result so that we don't try to generate this over and over
10309 // on every lookup, leaking memory and wasting time.
10310 ClassDecl->setFailedImplicitMoveConstructor();
10311 return 0;
10312 }
10313
10314 // Note that we have declared this constructor.
10315 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10316
10317 if (Scope *S = getScopeForContext(ClassDecl))
10318 PushOnScopeChains(MoveConstructor, S, false);
10319 ClassDecl->addDecl(MoveConstructor);
10320
10321 return MoveConstructor;
10322}
10323
10324void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10325 CXXConstructorDecl *MoveConstructor) {
10326 assert((MoveConstructor->isDefaulted() &&
10327 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010328 !MoveConstructor->doesThisDeclarationHaveABody() &&
10329 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010330 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10331
10332 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10333 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10334
Eli Friedmaneaf34142012-10-18 20:14:08 +000010335 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010336 DiagnosticErrorTrap Trap(Diags);
10337
David Blaikie3fc2f912013-01-17 05:26:25 +000010338 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010339 Trap.hasErrorOccurred()) {
10340 Diag(CurrentLocation, diag::note_member_synthesized_at)
10341 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10342 MoveConstructor->setInvalidDecl();
10343 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010344 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010345 MoveConstructor->setBody(ActOnCompoundStmt(
10346 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10347 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010348 }
10349
Eli Friedman276dd182013-09-05 00:02:25 +000010350 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010351
10352 if (ASTMutationListener *L = getASTMutationListener()) {
10353 L->CompletedImplicitDefinition(MoveConstructor);
10354 }
10355}
10356
Douglas Gregor74f7d502012-02-15 19:33:52 +000010357bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010358 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010359}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010360
10361void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010362 SourceLocation CurrentLocation,
10363 CXXConversionDecl *Conv) {
10364 CXXRecordDecl *Lambda = Conv->getParent();
10365 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10366 // If we are defining a specialization of a conversion to function-ptr
10367 // cache the deduced template arguments for this specialization
10368 // so that we can use them to retrieve the corresponding call-operator
10369 // and static-invoker.
10370 const TemplateArgumentList *DeducedTemplateArgs = 0;
10371
Douglas Gregor355efbb2012-02-17 03:02:34 +000010372
Faisal Vali571df122013-09-29 08:45:24 +000010373 // Retrieve the corresponding call-operator specialization.
10374 if (Lambda->isGenericLambda()) {
10375 assert(Conv->isFunctionTemplateSpecialization());
10376 FunctionTemplateDecl *CallOpTemplate =
10377 CallOp->getDescribedFunctionTemplate();
10378 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10379 void *InsertPos = 0;
10380 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10381 DeducedTemplateArgs->data(),
10382 DeducedTemplateArgs->size(),
10383 InsertPos);
10384 assert(CallOpSpec &&
10385 "Conversion operator must have a corresponding call operator");
10386 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10387 }
10388 // Mark the call operator referenced (and add to pending instantiations
10389 // if necessary).
10390 // For both the conversion and static-invoker template specializations
10391 // we construct their body's in this function, so no need to add them
10392 // to the PendingInstantiations.
10393 MarkFunctionReferenced(CurrentLocation, CallOp);
10394
Eli Friedmaneaf34142012-10-18 20:14:08 +000010395 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010396 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010397
10398 // Retreive the static invoker...
10399 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10400 // ... and get the corresponding specialization for a generic lambda.
10401 if (Lambda->isGenericLambda()) {
10402 assert(DeducedTemplateArgs &&
10403 "Must have deduced template arguments from Conversion Operator");
10404 FunctionTemplateDecl *InvokeTemplate =
10405 Invoker->getDescribedFunctionTemplate();
10406 void *InsertPos = 0;
10407 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10408 DeducedTemplateArgs->data(),
10409 DeducedTemplateArgs->size(),
10410 InsertPos);
10411 assert(InvokeSpec &&
10412 "Must have a corresponding static invoker specialization");
10413 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10414 }
10415 // Construct the body of the conversion function { return __invoke; }.
10416 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10417 VK_LValue, Conv->getLocation()).take();
10418 assert(FunctionRef && "Can't refer to __invoke function?");
10419 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10420 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10421 Conv->getLocation(),
10422 Conv->getLocation()));
10423
10424 Conv->markUsed(Context);
10425 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010426
Faisal Vali571df122013-09-29 08:45:24 +000010427 // Fill in the __invoke function with a dummy implementation. IR generation
10428 // will fill in the actual details.
10429 Invoker->markUsed(Context);
10430 Invoker->setReferenced();
10431 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10432
Douglas Gregord3b672c2012-02-16 01:06:16 +000010433 if (ASTMutationListener *L = getASTMutationListener()) {
10434 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010435 L->CompletedImplicitDefinition(Invoker);
10436 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010437}
10438
Faisal Vali571df122013-09-29 08:45:24 +000010439
10440
Douglas Gregord3b672c2012-02-16 01:06:16 +000010441void Sema::DefineImplicitLambdaToBlockPointerConversion(
10442 SourceLocation CurrentLocation,
10443 CXXConversionDecl *Conv)
10444{
Faisal Vali850da1a2013-09-29 17:08:32 +000010445 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010446
Eli Friedman276dd182013-09-05 00:02:25 +000010447 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010448
Eli Friedmaneaf34142012-10-18 20:14:08 +000010449 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010450 DiagnosticErrorTrap Trap(Diags);
10451
Douglas Gregored90df32012-02-22 05:02:47 +000010452 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010453 Expr *This = ActOnCXXThis(CurrentLocation).take();
10454 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010455
Eli Friedman98b01ed2012-03-01 04:01:32 +000010456 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10457 Conv->getLocation(),
10458 Conv, DerefThis);
10459
10460 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10461 // behavior. Note that only the general conversion function does this
10462 // (since it's unusable otherwise); in the case where we inline the
10463 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010464 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010465 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10466 CK_CopyAndAutoreleaseBlockObject,
10467 BuildBlock.get(), 0, VK_RValue);
10468
10469 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010470 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010471 Conv->setInvalidDecl();
10472 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010473 }
Douglas Gregored90df32012-02-22 05:02:47 +000010474
Douglas Gregored90df32012-02-22 05:02:47 +000010475 // Create the return statement that returns the block from the conversion
10476 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010477 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010478 if (Return.isInvalid()) {
10479 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10480 Conv->setInvalidDecl();
10481 return;
10482 }
10483
10484 // Set the body of the conversion function.
10485 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010486 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010487 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010488 Conv->getLocation()));
10489
Douglas Gregored90df32012-02-22 05:02:47 +000010490 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010491 if (ASTMutationListener *L = getASTMutationListener()) {
10492 L->CompletedImplicitDefinition(Conv);
10493 }
10494}
10495
Douglas Gregord2f70072012-03-10 06:53:13 +000010496/// \brief Determine whether the given list arguments contains exactly one
10497/// "real" (non-default) argument.
10498static bool hasOneRealArgument(MultiExprArg Args) {
10499 switch (Args.size()) {
10500 case 0:
10501 return false;
10502
10503 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010504 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010505 return false;
10506
10507 // fall through
10508 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010509 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010510 }
10511
10512 return false;
10513}
10514
John McCalldadc5752010-08-24 06:29:42 +000010515ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010516Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010517 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010518 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010519 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010520 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010521 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010522 unsigned ConstructKind,
10523 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010524 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010525
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010526 // C++0x [class.copy]p34:
10527 // When certain criteria are met, an implementation is allowed to
10528 // omit the copy/move construction of a class object, even if the
10529 // copy/move constructor and/or destructor for the object have
10530 // side effects. [...]
10531 // - when a temporary class object that has not been bound to a
10532 // reference (12.2) would be copied/moved to a class object
10533 // with the same cv-unqualified type, the copy/move operation
10534 // can be omitted by constructing the temporary object
10535 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010536 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010537 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010538 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010539 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010540 }
Mike Stump11289f42009-09-09 15:08:12 +000010541
10542 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010543 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010544 IsListInitialization, RequiresZeroInit,
10545 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010546}
10547
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010548/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10549/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010550ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010551Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10552 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010553 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010554 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010555 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010556 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010557 unsigned ConstructKind,
10558 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010559 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010560 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010561 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010562 HadMultipleCandidates,
10563 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010564 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10565 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010566}
10567
John McCall03c48482010-02-02 09:10:11 +000010568void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010569 if (VD->isInvalidDecl()) return;
10570
John McCall03c48482010-02-02 09:10:11 +000010571 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010572 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010573 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010574 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010575
Chandler Carruth86d17d32011-03-27 21:26:48 +000010576 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010577 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010578 CheckDestructorAccess(VD->getLocation(), Destructor,
10579 PDiag(diag::err_access_dtor_var)
10580 << VD->getDeclName()
10581 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010582 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010583
Chandler Carruth86d17d32011-03-27 21:26:48 +000010584 if (!VD->hasGlobalStorage()) return;
10585
10586 // Emit warning for non-trivial dtor in global scope (a real global,
10587 // class-static, function-static).
10588 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10589
10590 // TODO: this should be re-enabled for static locals by !CXAAtExit
10591 if (!VD->isStaticLocal())
10592 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010593}
10594
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010595/// \brief Given a constructor and the set of arguments provided for the
10596/// constructor, convert the arguments and add any required default arguments
10597/// to form a proper call to this constructor.
10598///
10599/// \returns true if an error occurred, false otherwise.
10600bool
10601Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10602 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010603 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010604 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010605 bool AllowExplicit,
10606 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010607 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10608 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010609 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010610
10611 const FunctionProtoType *Proto
10612 = Constructor->getType()->getAs<FunctionProtoType>();
10613 assert(Proto && "Constructor without a prototype?");
10614 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010615
10616 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010617 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010618 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010619 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010620 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010621
10622 VariadicCallType CallType =
10623 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010624 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010625 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010626 Proto, 0,
10627 llvm::makeArrayRef(Args, NumArgs),
10628 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010629 CallType, AllowExplicit,
10630 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010631 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010632
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010633 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010634
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010635 CheckConstructorCall(Constructor,
10636 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10637 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010638 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010639
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010640 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010641}
10642
Anders Carlssone363c8e2009-12-12 00:32:00 +000010643static inline bool
10644CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10645 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010646 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010647 if (isa<NamespaceDecl>(DC)) {
10648 return SemaRef.Diag(FnDecl->getLocation(),
10649 diag::err_operator_new_delete_declared_in_namespace)
10650 << FnDecl->getDeclName();
10651 }
10652
10653 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010654 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010655 return SemaRef.Diag(FnDecl->getLocation(),
10656 diag::err_operator_new_delete_declared_static)
10657 << FnDecl->getDeclName();
10658 }
10659
Anders Carlsson60659a82009-12-12 02:43:16 +000010660 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010661}
10662
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010663static inline bool
10664CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10665 CanQualType ExpectedResultType,
10666 CanQualType ExpectedFirstParamType,
10667 unsigned DependentParamTypeDiag,
10668 unsigned InvalidParamTypeDiag) {
10669 QualType ResultType =
10670 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10671
10672 // Check that the result type is not dependent.
10673 if (ResultType->isDependentType())
10674 return SemaRef.Diag(FnDecl->getLocation(),
10675 diag::err_operator_new_delete_dependent_result_type)
10676 << FnDecl->getDeclName() << ExpectedResultType;
10677
10678 // Check that the result type is what we expect.
10679 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10680 return SemaRef.Diag(FnDecl->getLocation(),
10681 diag::err_operator_new_delete_invalid_result_type)
10682 << FnDecl->getDeclName() << ExpectedResultType;
10683
10684 // A function template must have at least 2 parameters.
10685 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10686 return SemaRef.Diag(FnDecl->getLocation(),
10687 diag::err_operator_new_delete_template_too_few_parameters)
10688 << FnDecl->getDeclName();
10689
10690 // The function decl must have at least 1 parameter.
10691 if (FnDecl->getNumParams() == 0)
10692 return SemaRef.Diag(FnDecl->getLocation(),
10693 diag::err_operator_new_delete_too_few_parameters)
10694 << FnDecl->getDeclName();
10695
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010696 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010697 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10698 if (FirstParamType->isDependentType())
10699 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10700 << FnDecl->getDeclName() << ExpectedFirstParamType;
10701
10702 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010703 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010704 ExpectedFirstParamType)
10705 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10706 << FnDecl->getDeclName() << ExpectedFirstParamType;
10707
10708 return false;
10709}
10710
Anders Carlsson12308f42009-12-11 23:23:22 +000010711static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010712CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010713 // C++ [basic.stc.dynamic.allocation]p1:
10714 // A program is ill-formed if an allocation function is declared in a
10715 // namespace scope other than global scope or declared static in global
10716 // scope.
10717 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10718 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010719
10720 CanQualType SizeTy =
10721 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10722
10723 // C++ [basic.stc.dynamic.allocation]p1:
10724 // The return type shall be void*. The first parameter shall have type
10725 // std::size_t.
10726 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10727 SizeTy,
10728 diag::err_operator_new_dependent_param_type,
10729 diag::err_operator_new_param_type))
10730 return true;
10731
10732 // C++ [basic.stc.dynamic.allocation]p1:
10733 // The first parameter shall not have an associated default argument.
10734 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010735 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010736 diag::err_operator_new_default_arg)
10737 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10738
10739 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010740}
10741
10742static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010743CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010744 // C++ [basic.stc.dynamic.deallocation]p1:
10745 // A program is ill-formed if deallocation functions are declared in a
10746 // namespace scope other than global scope or declared static in global
10747 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010748 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10749 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010750
10751 // C++ [basic.stc.dynamic.deallocation]p2:
10752 // Each deallocation function shall return void and its first parameter
10753 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010754 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10755 SemaRef.Context.VoidPtrTy,
10756 diag::err_operator_delete_dependent_param_type,
10757 diag::err_operator_delete_param_type))
10758 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010759
Anders Carlsson12308f42009-12-11 23:23:22 +000010760 return false;
10761}
10762
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010763/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10764/// of this overloaded operator is well-formed. If so, returns false;
10765/// otherwise, emits appropriate diagnostics and returns true.
10766bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010767 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010768 "Expected an overloaded operator declaration");
10769
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010770 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10771
Mike Stump11289f42009-09-09 15:08:12 +000010772 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010773 // The allocation and deallocation functions, operator new,
10774 // operator new[], operator delete and operator delete[], are
10775 // described completely in 3.7.3. The attributes and restrictions
10776 // found in the rest of this subclause do not apply to them unless
10777 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010778 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010779 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010780
Anders Carlsson22f443f2009-12-12 00:26:23 +000010781 if (Op == OO_New || Op == OO_Array_New)
10782 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010783
10784 // C++ [over.oper]p6:
10785 // An operator function shall either be a non-static member
10786 // function or be a non-member function and have at least one
10787 // parameter whose type is a class, a reference to a class, an
10788 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010789 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10790 if (MethodDecl->isStatic())
10791 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010792 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010793 } else {
10794 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +000010795 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10796 ParamEnd = FnDecl->param_end();
10797 Param != ParamEnd; ++Param) {
10798 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010799 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10800 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010801 ClassOrEnumParam = true;
10802 break;
10803 }
10804 }
10805
Douglas Gregord69246b2008-11-17 16:14:12 +000010806 if (!ClassOrEnumParam)
10807 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010808 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010809 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010810 }
10811
10812 // C++ [over.oper]p8:
10813 // An operator function cannot have default arguments (8.3.6),
10814 // except where explicitly stated below.
10815 //
Mike Stump11289f42009-09-09 15:08:12 +000010816 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010817 // (C++ [over.call]p1).
10818 if (Op != OO_Call) {
10819 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10820 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010821 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +000010822 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010823 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010824 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010825 }
10826 }
10827
Douglas Gregor6cf08062008-11-10 13:38:07 +000010828 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10829 { false, false, false }
10830#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10831 , { Unary, Binary, MemberOnly }
10832#include "clang/Basic/OperatorKinds.def"
10833 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010834
Douglas Gregor6cf08062008-11-10 13:38:07 +000010835 bool CanBeUnaryOperator = OperatorUses[Op][0];
10836 bool CanBeBinaryOperator = OperatorUses[Op][1];
10837 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010838
10839 // C++ [over.oper]p8:
10840 // [...] Operator functions cannot have more or fewer parameters
10841 // than the number required for the corresponding operator, as
10842 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010843 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010844 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010845 if (Op != OO_Call &&
10846 ((NumParams == 1 && !CanBeUnaryOperator) ||
10847 (NumParams == 2 && !CanBeBinaryOperator) ||
10848 (NumParams < 1) || (NumParams > 2))) {
10849 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010850 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010851 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010852 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010853 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010854 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010855 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010856 assert(CanBeBinaryOperator &&
10857 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010858 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010859 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010860
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010861 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010862 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010863 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010864
Douglas Gregord69246b2008-11-17 16:14:12 +000010865 // Overloaded operators other than operator() cannot be variadic.
10866 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010867 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010868 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010869 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010870 }
10871
10872 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010873 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10874 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010875 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010876 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010877 }
10878
10879 // C++ [over.inc]p1:
10880 // The user-defined function called operator++ implements the
10881 // prefix and postfix ++ operator. If this function is a member
10882 // function with no parameters, or a non-member function with one
10883 // parameter of class or enumeration type, it defines the prefix
10884 // increment operator ++ for objects of that type. If the function
10885 // is a member function with one parameter (which shall be of type
10886 // int) or a non-member function with two parameters (the second
10887 // of which shall be of type int), it defines the postfix
10888 // increment operator ++ for objects of that type.
10889 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10890 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10891 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +000010892 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010893 ParamIsInt = BT->getKind() == BuiltinType::Int;
10894
Chris Lattner2b786902008-11-21 07:50:02 +000010895 if (!ParamIsInt)
10896 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010897 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010898 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010899 }
10900
Douglas Gregord69246b2008-11-17 16:14:12 +000010901 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010902}
Chris Lattner3b024a32008-12-17 07:09:26 +000010903
Alexis Huntc88db062010-01-13 09:01:02 +000010904/// CheckLiteralOperatorDeclaration - Check whether the declaration
10905/// of this literal operator function is well-formed. If so, returns
10906/// false; otherwise, emits appropriate diagnostics and returns true.
10907bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010908 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010909 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10910 << FnDecl->getDeclName();
10911 return true;
10912 }
10913
Richard Smith72eebee2012-03-04 09:41:16 +000010914 if (FnDecl->isExternC()) {
10915 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10916 return true;
10917 }
10918
Alexis Huntc88db062010-01-13 09:01:02 +000010919 bool Valid = false;
10920
Richard Smithbcc22fc2012-03-09 08:00:36 +000010921 // This might be the definition of a literal operator template.
10922 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10923 // This might be a specialization of a literal operator template.
10924 if (!TpDecl)
10925 TpDecl = FnDecl->getPrimaryTemplate();
10926
Richard Smithb8b41d32013-10-07 19:57:58 +000010927 // template <char...> type operator "" name() and
10928 // template <class T, T...> type operator "" name() are the only valid
10929 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010930 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010931 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010932 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010933 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10934 if (Params->size() == 1) {
10935 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010936 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010937
Alexis Hunt7dd26172010-04-07 23:11:06 +000010938 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010939 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10940 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10941 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010942 } else if (Params->size() == 2) {
10943 TemplateTypeParmDecl *PmType =
10944 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10945 NonTypeTemplateParmDecl *PmArgs =
10946 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10947
10948 // The second template parameter must be a parameter pack with the
10949 // first template parameter as its type.
10950 if (PmType && PmArgs &&
10951 !PmType->isTemplateParameterPack() &&
10952 PmArgs->isTemplateParameterPack()) {
10953 const TemplateTypeParmType *TArgs =
10954 PmArgs->getType()->getAs<TemplateTypeParmType>();
10955 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10956 TArgs->getIndex() == PmType->getIndex()) {
10957 Valid = true;
10958 if (ActiveTemplateInstantiations.empty())
10959 Diag(FnDecl->getLocation(),
10960 diag::ext_string_literal_operator_template);
10961 }
10962 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010963 }
10964 }
Richard Smith72eebee2012-03-04 09:41:16 +000010965 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010966 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010967 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10968
Richard Smith72eebee2012-03-04 09:41:16 +000010969 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010970
Alexis Hunt079a6f72010-04-07 22:57:35 +000010971 // unsigned long long int, long double, and any character type are allowed
10972 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010973 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10974 Context.hasSameType(T, Context.LongDoubleTy) ||
10975 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010976 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010977 Context.hasSameType(T, Context.Char16Ty) ||
10978 Context.hasSameType(T, Context.Char32Ty)) {
10979 if (++Param == FnDecl->param_end())
10980 Valid = true;
10981 goto FinishedParams;
10982 }
10983
Alexis Hunt079a6f72010-04-07 22:57:35 +000010984 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010985 const PointerType *PT = T->getAs<PointerType>();
10986 if (!PT)
10987 goto FinishedParams;
10988 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010989 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010990 goto FinishedParams;
10991 T = T.getUnqualifiedType();
10992
10993 // Move on to the second parameter;
10994 ++Param;
10995
10996 // If there is no second parameter, the first must be a const char *
10997 if (Param == FnDecl->param_end()) {
10998 if (Context.hasSameType(T, Context.CharTy))
10999 Valid = true;
11000 goto FinishedParams;
11001 }
11002
11003 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11004 // are allowed as the first parameter to a two-parameter function
11005 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011006 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011007 Context.hasSameType(T, Context.Char16Ty) ||
11008 Context.hasSameType(T, Context.Char32Ty)))
11009 goto FinishedParams;
11010
11011 // The second and final parameter must be an std::size_t
11012 T = (*Param)->getType().getUnqualifiedType();
11013 if (Context.hasSameType(T, Context.getSizeType()) &&
11014 ++Param == FnDecl->param_end())
11015 Valid = true;
11016 }
11017
11018 // FIXME: This diagnostic is absolutely terrible.
11019FinishedParams:
11020 if (!Valid) {
11021 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11022 << FnDecl->getDeclName();
11023 return true;
11024 }
11025
Richard Smith768cecc2012-03-09 08:16:22 +000011026 // A parameter-declaration-clause containing a default argument is not
11027 // equivalent to any of the permitted forms.
11028 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11029 ParamEnd = FnDecl->param_end();
11030 Param != ParamEnd; ++Param) {
11031 if ((*Param)->hasDefaultArg()) {
11032 Diag((*Param)->getDefaultArgRange().getBegin(),
11033 diag::err_literal_operator_default_argument)
11034 << (*Param)->getDefaultArgRange();
11035 break;
11036 }
11037 }
11038
Richard Smith0df56f42012-03-08 02:39:21 +000011039 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011040 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11041 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011042 // C++11 [usrlit.suffix]p1:
11043 // Literal suffix identifiers that do not start with an underscore
11044 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011045 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11046 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011047 }
Richard Smith0df56f42012-03-08 02:39:21 +000011048
Alexis Huntc88db062010-01-13 09:01:02 +000011049 return false;
11050}
11051
Douglas Gregor07665a62009-01-05 19:45:36 +000011052/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11053/// linkage specification, including the language and (if present)
11054/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11055/// the location of the language string literal, which is provided
11056/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11057/// the '{' brace. Otherwise, this linkage specification does not
11058/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011059Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11060 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011061 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +000011062 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +000011063 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011064 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011065 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011066 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011067 Language = LinkageSpecDecl::lang_cxx;
11068 else {
Douglas Gregor07665a62009-01-05 19:45:36 +000011069 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +000011070 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011071 }
Mike Stump11289f42009-09-09 15:08:12 +000011072
Chris Lattner438e5012008-12-17 07:13:27 +000011073 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011074
Douglas Gregor07665a62009-01-05 19:45:36 +000011075 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011076 ExternLoc, LangLoc, Language,
11077 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011078 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011079 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011080 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011081}
11082
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011083/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011084/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11085/// valid, it's the position of the closing '}' brace in a linkage
11086/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011087Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011088 Decl *LinkageSpec,
11089 SourceLocation RBraceLoc) {
11090 if (LinkageSpec) {
11091 if (RBraceLoc.isValid()) {
11092 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11093 LSDecl->setRBraceLoc(RBraceLoc);
11094 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011095 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011096 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011097 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011098}
11099
Michael Han84324352013-02-22 17:15:32 +000011100Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11101 AttributeList *AttrList,
11102 SourceLocation SemiLoc) {
11103 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11104 // Attribute declarations appertain to empty declaration so we handle
11105 // them here.
11106 if (AttrList)
11107 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011108
Michael Han84324352013-02-22 17:15:32 +000011109 CurContext->addDecl(ED);
11110 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011111}
11112
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011113/// \brief Perform semantic analysis for the variable declaration that
11114/// occurs within a C++ catch clause, returning the newly-created
11115/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011116VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011117 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011118 SourceLocation StartLoc,
11119 SourceLocation Loc,
11120 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011121 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011122 QualType ExDeclType = TInfo->getType();
11123
Sebastian Redl54c04d42008-12-22 19:15:10 +000011124 // Arrays and functions decay.
11125 if (ExDeclType->isArrayType())
11126 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11127 else if (ExDeclType->isFunctionType())
11128 ExDeclType = Context.getPointerType(ExDeclType);
11129
11130 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11131 // The exception-declaration shall not denote a pointer or reference to an
11132 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011133 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011134 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011135 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011136 Invalid = true;
11137 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011138
Sebastian Redl54c04d42008-12-22 19:15:10 +000011139 QualType BaseType = ExDeclType;
11140 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011141 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011142 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011143 BaseType = Ptr->getPointeeType();
11144 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011145 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011146 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011147 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011148 BaseType = Ref->getPointeeType();
11149 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011150 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011151 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011152 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011153 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011154 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011155
Mike Stump11289f42009-09-09 15:08:12 +000011156 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011157 RequireNonAbstractType(Loc, ExDeclType,
11158 diag::err_abstract_type_in_decl,
11159 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011160 Invalid = true;
11161
John McCall2ca705e2010-07-24 00:37:23 +000011162 // Only the non-fragile NeXT runtime currently supports C++ catches
11163 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011164 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011165 QualType T = ExDeclType;
11166 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11167 T = RT->getPointeeType();
11168
11169 if (T->isObjCObjectType()) {
11170 Diag(Loc, diag::err_objc_object_catch);
11171 Invalid = true;
11172 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011173 // FIXME: should this be a test for macosx-fragile specifically?
11174 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011175 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011176 }
11177 }
11178
Abramo Bagnaradff19302011-03-08 08:55:46 +000011179 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011180 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011181 ExDecl->setExceptionVariable(true);
11182
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011183 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011184 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011185 Invalid = true;
11186
Douglas Gregor750734c2011-07-06 18:14:43 +000011187 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011188 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011189 // Insulate this from anything else we might currently be parsing.
11190 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11191
Douglas Gregor6de584c2010-03-05 23:38:39 +000011192 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011193 // The object declared in an exception-declaration or, if the
11194 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011195 // copy-initialized (8.5) from the exception object. [...]
11196 // The object is destroyed when the handler exits, after the destruction
11197 // of any automatic objects initialized within the handler.
11198 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011199 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011200 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011201 QualType initType = ExDeclType;
11202
11203 InitializedEntity entity =
11204 InitializedEntity::InitializeVariable(ExDecl);
11205 InitializationKind initKind =
11206 InitializationKind::CreateCopy(Loc, SourceLocation());
11207
11208 Expr *opaqueValue =
11209 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011210 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11211 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011212 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011213 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011214 else {
11215 // If the constructor used was non-trivial, set this as the
11216 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011217 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011218 if (!construct->getConstructor()->isTrivial()) {
11219 Expr *init = MaybeCreateExprWithCleanups(construct);
11220 ExDecl->setInit(init);
11221 }
11222
11223 // And make sure it's destructable.
11224 FinalizeVarWithDestructor(ExDecl, recordType);
11225 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011226 }
11227 }
11228
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011229 if (Invalid)
11230 ExDecl->setInvalidDecl();
11231
11232 return ExDecl;
11233}
11234
11235/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11236/// handler.
John McCall48871652010-08-21 09:40:31 +000011237Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011238 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011239 bool Invalid = D.isInvalidType();
11240
11241 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011242 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11243 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011244 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11245 D.getIdentifierLoc());
11246 Invalid = true;
11247 }
11248
Sebastian Redl54c04d42008-12-22 19:15:10 +000011249 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011250 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011251 LookupOrdinaryName,
11252 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011253 // The scope should be freshly made just for us. There is just no way
11254 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011255 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011256 if (PrevDecl->isTemplateParameter()) {
11257 // Maybe we will complain about the shadowed template parameter.
11258 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011259 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011260 }
11261 }
11262
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011263 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011264 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11265 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011266 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011267 }
11268
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011269 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011270 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011271 D.getIdentifierLoc(),
11272 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011273 if (Invalid)
11274 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011275
Sebastian Redl54c04d42008-12-22 19:15:10 +000011276 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011277 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011278 PushOnScopeChains(ExDecl, S);
11279 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011280 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011281
Douglas Gregor758a8692009-06-17 21:51:59 +000011282 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011283 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011284}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011285
Abramo Bagnaraea947882011-03-08 16:41:52 +000011286Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011287 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011288 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011289 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011290 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011291
Richard Smithded9c2e2012-07-11 22:37:56 +000011292 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11293 return 0;
11294
11295 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11296 AssertMessage, RParenLoc, false);
11297}
11298
11299Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11300 Expr *AssertExpr,
11301 StringLiteral *AssertMessage,
11302 SourceLocation RParenLoc,
11303 bool Failed) {
11304 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11305 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011306 // In a static_assert-declaration, the constant-expression shall be a
11307 // constant expression that can be contextually converted to bool.
11308 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11309 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011310 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011311
Richard Smith902ca212011-12-14 23:32:26 +000011312 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011313 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011314 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011315 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011316 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011317
Richard Smithded9c2e2012-07-11 22:37:56 +000011318 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011319 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011320 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011321 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011322 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011323 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011324 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011325 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011326 }
Mike Stump11289f42009-09-09 15:08:12 +000011327
Abramo Bagnaraea947882011-03-08 16:41:52 +000011328 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011329 AssertExpr, AssertMessage, RParenLoc,
11330 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011331
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011332 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011333 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011334}
Sebastian Redlf769df52009-03-24 22:27:57 +000011335
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011336/// \brief Perform semantic analysis of the given friend type declaration.
11337///
11338/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011339FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011340 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011341 TypeSourceInfo *TSInfo) {
11342 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11343
11344 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011345 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011346
Richard Smithc8239732011-10-18 21:39:00 +000011347 // C++03 [class.friend]p2:
11348 // An elaborated-type-specifier shall be used in a friend declaration
11349 // for a class.*
11350 //
11351 // * The class-key of the elaborated-type-specifier is required.
11352 if (!ActiveTemplateInstantiations.empty()) {
11353 // Do not complain about the form of friend template types during
11354 // template instantiation; we will already have complained when the
11355 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011356 } else {
11357 if (!T->isElaboratedTypeSpecifier()) {
11358 // If we evaluated the type to a record type, suggest putting
11359 // a tag in front.
11360 if (const RecordType *RT = T->getAs<RecordType>()) {
11361 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011362
Nick Lewycky36722d22013-02-06 05:59:33 +000011363 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011364
Nick Lewycky36722d22013-02-06 05:59:33 +000011365 Diag(TypeRange.getBegin(),
11366 getLangOpts().CPlusPlus11 ?
11367 diag::warn_cxx98_compat_unelaborated_friend_type :
11368 diag::ext_unelaborated_friend_type)
11369 << (unsigned) RD->getTagKind()
11370 << T
11371 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11372 InsertionText);
11373 } else {
11374 Diag(FriendLoc,
11375 getLangOpts().CPlusPlus11 ?
11376 diag::warn_cxx98_compat_nonclass_type_friend :
11377 diag::ext_nonclass_type_friend)
11378 << T
11379 << TypeRange;
11380 }
11381 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011382 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011383 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011384 diag::warn_cxx98_compat_enum_friend :
11385 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011386 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011387 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011388 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011389
Nick Lewycky36722d22013-02-06 05:59:33 +000011390 // C++11 [class.friend]p3:
11391 // A friend declaration that does not declare a function shall have one
11392 // of the following forms:
11393 // friend elaborated-type-specifier ;
11394 // friend simple-type-specifier ;
11395 // friend typename-specifier ;
11396 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11397 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11398 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011399
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011400 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011401 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011402 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011403 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011404}
11405
John McCallace48cd2010-10-19 01:40:49 +000011406/// Handle a friend tag declaration where the scope specifier was
11407/// templated.
11408Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11409 unsigned TagSpec, SourceLocation TagLoc,
11410 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011411 IdentifierInfo *Name,
11412 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011413 AttributeList *Attr,
11414 MultiTemplateParamsArg TempParamLists) {
11415 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11416
11417 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011418 bool Invalid = false;
11419
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011420 if (TemplateParameterList *TemplateParams =
11421 MatchTemplateParametersToScopeSpecifier(
11422 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11423 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011424 if (TemplateParams->size() > 0) {
11425 // This is a declaration of a class template.
11426 if (Invalid)
11427 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011428
Eric Christopher6f228b52011-07-21 05:34:24 +000011429 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11430 SS, Name, NameLoc, Attr,
11431 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011432 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011433 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011434 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011435 } else {
11436 // The "template<>" header is extraneous.
11437 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11438 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11439 isExplicitSpecialization = true;
11440 }
11441 }
11442
11443 if (Invalid) return 0;
11444
John McCallace48cd2010-10-19 01:40:49 +000011445 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011446 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011447 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011448 isAllExplicitSpecializations = false;
11449 break;
11450 }
11451 }
11452
11453 // FIXME: don't ignore attributes.
11454
11455 // If it's explicit specializations all the way down, just forget
11456 // about the template header and build an appropriate non-templated
11457 // friend. TODO: for source fidelity, remember the headers.
11458 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011459 if (SS.isEmpty()) {
11460 bool Owned = false;
11461 bool IsDependent = false;
11462 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11463 Attr, AS_public,
11464 /*ModulePrivateLoc=*/SourceLocation(),
11465 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011466 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011467 /*ScopedEnumUsesClassTag=*/false,
11468 /*UnderlyingType=*/TypeResult());
11469 }
11470
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011471 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011472 ElaboratedTypeKeyword Keyword
11473 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011474 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011475 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011476 if (T.isNull())
11477 return 0;
11478
11479 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11480 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011481 DependentNameTypeLoc TL =
11482 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011483 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011484 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011485 TL.setNameLoc(NameLoc);
11486 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011487 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011488 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011489 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011490 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011491 }
11492
11493 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011494 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011495 Friend->setAccess(AS_public);
11496 CurContext->addDecl(Friend);
11497 return Friend;
11498 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011499
11500 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11501
11502
John McCallace48cd2010-10-19 01:40:49 +000011503
11504 // Handle the case of a templated-scope friend class. e.g.
11505 // template <class T> class A<T>::B;
11506 // FIXME: we don't support these right now.
11507 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11508 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11509 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011510 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011511 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011512 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011513 TL.setNameLoc(NameLoc);
11514
11515 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011516 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011517 Friend->setAccess(AS_public);
11518 Friend->setUnsupportedFriend(true);
11519 CurContext->addDecl(Friend);
11520 return Friend;
11521}
11522
11523
John McCall11083da2009-09-16 22:47:08 +000011524/// Handle a friend type declaration. This works in tandem with
11525/// ActOnTag.
11526///
11527/// Notes on friend class templates:
11528///
11529/// We generally treat friend class declarations as if they were
11530/// declaring a class. So, for example, the elaborated type specifier
11531/// in a friend declaration is required to obey the restrictions of a
11532/// class-head (i.e. no typedefs in the scope chain), template
11533/// parameters are required to match up with simple template-ids, &c.
11534/// However, unlike when declaring a template specialization, it's
11535/// okay to refer to a template specialization without an empty
11536/// template parameter declaration, e.g.
11537/// friend class A<T>::B<unsigned>;
11538/// We permit this as a special case; if there are any template
11539/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011540/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011541Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011542 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011543 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011544
11545 assert(DS.isFriendSpecified());
11546 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11547
John McCall11083da2009-09-16 22:47:08 +000011548 // Try to convert the decl specifier to a type. This works for
11549 // friend templates because ActOnTag never produces a ClassTemplateDecl
11550 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011551 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011552 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11553 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011554 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011555 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011556
Douglas Gregor6c110f32010-12-16 01:14:37 +000011557 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11558 return 0;
11559
John McCall11083da2009-09-16 22:47:08 +000011560 // This is definitely an error in C++98. It's probably meant to
11561 // be forbidden in C++0x, too, but the specification is just
11562 // poorly written.
11563 //
11564 // The problem is with declarations like the following:
11565 // template <T> friend A<T>::foo;
11566 // where deciding whether a class C is a friend or not now hinges
11567 // on whether there exists an instantiation of A that causes
11568 // 'foo' to equal C. There are restrictions on class-heads
11569 // (which we declare (by fiat) elaborated friend declarations to
11570 // be) that makes this tractable.
11571 //
11572 // FIXME: handle "template <> friend class A<T>;", which
11573 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011574 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011575 Diag(Loc, diag::err_tagless_friend_type_template)
11576 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011577 return 0;
John McCall11083da2009-09-16 22:47:08 +000011578 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011579
John McCallaa74a0c2009-08-28 07:59:38 +000011580 // C++98 [class.friend]p1: A friend of a class is a function
11581 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011582 // This is fixed in DR77, which just barely didn't make the C++03
11583 // deadline. It's also a very silly restriction that seriously
11584 // affects inner classes and which nobody else seems to implement;
11585 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011586 //
11587 // But note that we could warn about it: it's always useless to
11588 // friend one of your own members (it's not, however, worthless to
11589 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011590
John McCall11083da2009-09-16 22:47:08 +000011591 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011592 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011593 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011594 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011595 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011596 TSI,
John McCall11083da2009-09-16 22:47:08 +000011597 DS.getFriendSpecLoc());
11598 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011599 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011600
11601 if (!D)
John McCall48871652010-08-21 09:40:31 +000011602 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011603
John McCall11083da2009-09-16 22:47:08 +000011604 D->setAccess(AS_public);
11605 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011606
John McCall48871652010-08-21 09:40:31 +000011607 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011608}
11609
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011610NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11611 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011612 const DeclSpec &DS = D.getDeclSpec();
11613
11614 assert(DS.isFriendSpecified());
11615 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11616
11617 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011618 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011619
11620 // C++ [class.friend]p1
11621 // A friend of a class is a function or class....
11622 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011623 // It *doesn't* see through dependent types, which is correct
11624 // according to [temp.arg.type]p3:
11625 // If a declaration acquires a function type through a
11626 // type dependent on a template-parameter and this causes
11627 // a declaration that does not use the syntactic form of a
11628 // function declarator to have a function type, the program
11629 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011630 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011631 Diag(Loc, diag::err_unexpected_friend);
11632
11633 // It might be worthwhile to try to recover by creating an
11634 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011635 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011636 }
11637
11638 // C++ [namespace.memdef]p3
11639 // - If a friend declaration in a non-local class first declares a
11640 // class or function, the friend class or function is a member
11641 // of the innermost enclosing namespace.
11642 // - The name of the friend is not found by simple name lookup
11643 // until a matching declaration is provided in that namespace
11644 // scope (either before or after the class declaration granting
11645 // friendship).
11646 // - If a friend function is called, its name may be found by the
11647 // name lookup that considers functions from namespaces and
11648 // classes associated with the types of the function arguments.
11649 // - When looking for a prior declaration of a class or a function
11650 // declared as a friend, scopes outside the innermost enclosing
11651 // namespace scope are not considered.
11652
John McCallde3fd222010-10-12 23:13:28 +000011653 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011654 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11655 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011656 assert(Name);
11657
Douglas Gregor6c110f32010-12-16 01:14:37 +000011658 // Check for unexpanded parameter packs.
11659 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11660 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11661 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11662 return 0;
11663
John McCall07e91c02009-08-06 02:15:43 +000011664 // The context we found the declaration in, or in which we should
11665 // create the declaration.
11666 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011667 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011668 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011669 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011670
Richard Smith114394f2013-08-09 04:35:01 +000011671 // There are five cases here.
11672 // - There's no scope specifier and we're in a local class. Only look
11673 // for functions declared in the immediately-enclosing block scope.
11674 // We recover from invalid scope qualifiers as if they just weren't there.
11675 FunctionDecl *FunctionContainingLocalClass = 0;
11676 if ((SS.isInvalid() || !SS.isSet()) &&
11677 (FunctionContainingLocalClass =
11678 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11679 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011680 // If a friend declaration appears in a local class and the name
11681 // specified is an unqualified name, a prior declaration is
11682 // looked up without considering scopes that are outside the
11683 // innermost enclosing non-class scope. For a friend function
11684 // declaration, if there is no prior declaration, the program is
11685 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011686
11687 // Find the innermost enclosing non-class scope. This is the block
11688 // scope containing the local class definition (or for a nested class,
11689 // the outer local class).
11690 DCScope = S->getFnParent();
11691
11692 // Look up the function name in the scope.
11693 Previous.clear(LookupLocalFriendName);
11694 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11695
11696 if (!Previous.empty()) {
11697 // All possible previous declarations must have the same context:
11698 // either they were declared at block scope or they are members of
11699 // one of the enclosing local classes.
11700 DC = Previous.getRepresentativeDecl()->getDeclContext();
11701 } else {
11702 // This is ill-formed, but provide the context that we would have
11703 // declared the function in, if we were permitted to, for error recovery.
11704 DC = FunctionContainingLocalClass;
11705 }
Richard Smith541b38b2013-09-20 01:15:31 +000011706 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011707
11708 // C++ [class.friend]p6:
11709 // A function can be defined in a friend declaration of a class if and
11710 // only if the class is a non-local class (9.8), the function name is
11711 // unqualified, and the function has namespace scope.
11712 if (D.isFunctionDefinition()) {
11713 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11714 }
11715
11716 // - There's no scope specifier, in which case we just go to the
11717 // appropriate scope and look for a function or function template
11718 // there as appropriate.
11719 } else if (SS.isInvalid() || !SS.isSet()) {
11720 // C++11 [namespace.memdef]p3:
11721 // If the name in a friend declaration is neither qualified nor
11722 // a template-id and the declaration is a function or an
11723 // elaborated-type-specifier, the lookup to determine whether
11724 // the entity has been previously declared shall not consider
11725 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011726 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011727
John McCallf7cfb222010-10-13 05:45:15 +000011728 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011729 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011730
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011731 // Skip class contexts. If someone can cite chapter and verse
11732 // for this behavior, that would be nice --- it's what GCC and
11733 // EDG do, and it seems like a reasonable intent, but the spec
11734 // really only says that checks for unqualified existing
11735 // declarations should stop at the nearest enclosing namespace,
11736 // not that they should only consider the nearest enclosing
11737 // namespace.
11738 while (DC->isRecord())
11739 DC = DC->getParent();
11740
11741 DeclContext *LookupDC = DC;
11742 while (LookupDC->isTransparentContext())
11743 LookupDC = LookupDC->getParent();
11744
11745 while (true) {
11746 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011747
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011748 if (!Previous.empty()) {
11749 DC = LookupDC;
11750 break;
John McCallf4776592010-10-14 22:22:28 +000011751 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011752
11753 if (isTemplateId) {
11754 if (isa<TranslationUnitDecl>(LookupDC)) break;
11755 } else {
11756 if (LookupDC->isFileContext()) break;
11757 }
11758 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011759 }
11760
John McCallccbc0322010-10-13 06:22:15 +000011761 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011762
John McCallde3fd222010-10-12 23:13:28 +000011763 // - There's a non-dependent scope specifier, in which case we
11764 // compute it and do a previous lookup there for a function
11765 // or function template.
11766 } else if (!SS.getScopeRep()->isDependent()) {
11767 DC = computeDeclContext(SS);
11768 if (!DC) return 0;
11769
11770 if (RequireCompleteDeclContext(SS, DC)) return 0;
11771
11772 LookupQualifiedName(Previous, DC);
11773
11774 // Ignore things found implicitly in the wrong scope.
11775 // TODO: better diagnostics for this case. Suggesting the right
11776 // qualified scope would be nice...
11777 LookupResult::Filter F = Previous.makeFilter();
11778 while (F.hasNext()) {
11779 NamedDecl *D = F.next();
11780 if (!DC->InEnclosingNamespaceSetOf(
11781 D->getDeclContext()->getRedeclContext()))
11782 F.erase();
11783 }
11784 F.done();
11785
11786 if (Previous.empty()) {
11787 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011788 Diag(Loc, diag::err_qualified_friend_not_found)
11789 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011790 return 0;
11791 }
11792
11793 // C++ [class.friend]p1: A friend of a class is a function or
11794 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011795 if (DC->Equals(CurContext))
11796 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011797 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011798 diag::warn_cxx98_compat_friend_is_member :
11799 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011800
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011801 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011802 // C++ [class.friend]p6:
11803 // A function can be defined in a friend declaration of a class if and
11804 // only if the class is a non-local class (9.8), the function name is
11805 // unqualified, and the function has namespace scope.
11806 SemaDiagnosticBuilder DB
11807 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11808
11809 DB << SS.getScopeRep();
11810 if (DC->isFileContext())
11811 DB << FixItHint::CreateRemoval(SS.getRange());
11812 SS.clear();
11813 }
John McCallde3fd222010-10-12 23:13:28 +000011814
11815 // - There's a scope specifier that does not match any template
11816 // parameter lists, in which case we use some arbitrary context,
11817 // create a method or method template, and wait for instantiation.
11818 // - There's a scope specifier that does match some template
11819 // parameter lists, which we don't handle right now.
11820 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011821 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011822 // C++ [class.friend]p6:
11823 // A function can be defined in a friend declaration of a class if and
11824 // only if the class is a non-local class (9.8), the function name is
11825 // unqualified, and the function has namespace scope.
11826 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11827 << SS.getScopeRep();
11828 }
11829
John McCallde3fd222010-10-12 23:13:28 +000011830 DC = CurContext;
11831 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011832 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011833
John McCallf7cfb222010-10-13 05:45:15 +000011834 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011835 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011836 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11837 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11838 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011839 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011840 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11841 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011842 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011843 }
John McCall07e91c02009-08-06 02:15:43 +000011844 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011845
Douglas Gregordd847ba2011-11-03 16:37:14 +000011846 // FIXME: This is an egregious hack to cope with cases where the scope stack
11847 // does not contain the declaration context, i.e., in an out-of-line
11848 // definition of a class.
11849 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11850 if (!DCScope) {
11851 FakeDCScope.setEntity(DC);
11852 DCScope = &FakeDCScope;
11853 }
Richard Smith114394f2013-08-09 04:35:01 +000011854
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011855 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011856 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011857 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011858 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011859
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011860 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011861
Richard Smith114394f2013-08-09 04:35:01 +000011862 // If we performed typo correction, we might have added a scope specifier
11863 // and changed the decl context.
11864 DC = ND->getDeclContext();
11865
John McCall759e32b2009-08-31 22:39:49 +000011866 // Add the function declaration to the appropriate lookup tables,
11867 // adjusting the redeclarations list as necessary. We don't
11868 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011869 //
John McCall759e32b2009-08-31 22:39:49 +000011870 // Also update the scope-based lookup if the target context's
11871 // lookup context is in lexical scope.
11872 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011873 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011874 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011875 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011876 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011877 }
John McCallaa74a0c2009-08-28 07:59:38 +000011878
11879 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011880 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011881 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011882 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011883 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011884
John McCalla0a96892012-08-10 03:15:35 +000011885 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011886 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011887 } else {
11888 if (DC->isRecord()) CheckFriendAccess(ND);
11889
John McCall2c2eb122010-10-16 06:59:13 +000011890 FunctionDecl *FD;
11891 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11892 FD = FTD->getTemplatedDecl();
11893 else
11894 FD = cast<FunctionDecl>(ND);
11895
David Majnemer502b0ed2013-06-25 23:09:30 +000011896 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11897 // default argument expression, that declaration shall be a definition
11898 // and shall be the only declaration of the function or function
11899 // template in the translation unit.
11900 if (functionDeclHasDefaultArgument(FD)) {
11901 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11902 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11903 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11904 } else if (!D.isFunctionDefinition())
11905 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11906 }
11907
John McCall2c2eb122010-10-16 06:59:13 +000011908 // Mark templated-scope function declarations as unsupported.
11909 if (FD->getNumTemplateParameterLists())
11910 FrD->setUnsupportedFriend(true);
11911 }
John McCallde3fd222010-10-12 23:13:28 +000011912
John McCall48871652010-08-21 09:40:31 +000011913 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011914}
11915
John McCall48871652010-08-21 09:40:31 +000011916void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11917 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011918
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011919 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011920 if (!Fn) {
11921 Diag(DelLoc, diag::err_deleted_non_function);
11922 return;
11923 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011924
Douglas Gregorec9fd132012-01-14 16:38:05 +000011925 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011926 // Don't consider the implicit declaration we generate for explicit
11927 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikieaf031a92012-06-29 18:00:25 +000011928 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11929 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011930 Diag(DelLoc, diag::err_deleted_decl_not_first);
11931 Diag(Prev->getLocation(), diag::note_previous_declaration);
11932 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011933 // If the declaration wasn't the first, we delete the function anyway for
11934 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011935 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011936 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011937
11938 if (Fn->isDeleted())
11939 return;
11940
11941 // See if we're deleting a function which is already known to override a
11942 // non-deleted virtual function.
11943 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11944 bool IssuedDiagnostic = false;
11945 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11946 E = MD->end_overridden_methods();
11947 I != E; ++I) {
11948 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11949 if (!IssuedDiagnostic) {
11950 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11951 IssuedDiagnostic = true;
11952 }
11953 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11954 }
11955 }
11956 }
11957
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011958 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011959}
Sebastian Redl4c018662009-04-27 21:33:24 +000011960
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011961void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011962 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011963
11964 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011965 if (MD->getParent()->isDependentType()) {
11966 MD->setDefaulted();
11967 MD->setExplicitlyDefaulted();
11968 return;
11969 }
11970
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011971 CXXSpecialMember Member = getSpecialMember(MD);
11972 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011973 if (!MD->isInvalidDecl())
11974 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011975 return;
11976 }
11977
11978 MD->setDefaulted();
11979 MD->setExplicitlyDefaulted();
11980
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011981 // If this definition appears within the record, do the checking when
11982 // the record is complete.
11983 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000011984 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011985 // Find the uninstantiated declaration that actually had the '= default'
11986 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000011987 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011988
Richard Smith3901dfe2013-03-27 00:22:47 +000011989 // If the method was defaulted on its first declaration, we will have
11990 // already performed the checking in CheckCompletedCXXClass. Such a
11991 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011992 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011993 return;
11994
Richard Smithd3b5c9082012-07-27 04:22:15 +000011995 CheckExplicitlyDefaultedSpecialMember(MD);
11996
Richard Smithbd305122012-12-11 01:14:52 +000011997 // The exception specification is needed because we are defining the
11998 // function.
11999 ResolveExceptionSpec(DefaultLoc,
12000 MD->getType()->castAs<FunctionProtoType>());
12001
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012002 if (MD->isInvalidDecl())
12003 return;
12004
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012005 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012006 case CXXDefaultConstructor:
12007 DefineImplicitDefaultConstructor(DefaultLoc,
12008 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012009 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012010 case CXXCopyConstructor:
12011 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012012 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012013 case CXXCopyAssignment:
12014 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012015 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012016 case CXXDestructor:
12017 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012018 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012019 case CXXMoveConstructor:
12020 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012021 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012022 case CXXMoveAssignment:
12023 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012024 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012025 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012026 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012027 }
12028 } else {
12029 Diag(DefaultLoc, diag::err_default_special_members);
12030 }
12031}
12032
Sebastian Redl4c018662009-04-27 21:33:24 +000012033static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012034 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012035 Stmt *SubStmt = *CI;
12036 if (!SubStmt)
12037 continue;
12038 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012039 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012040 diag::err_return_in_constructor_handler);
12041 if (!isa<Expr>(SubStmt))
12042 SearchForReturnInStmt(Self, SubStmt);
12043 }
12044}
12045
12046void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12047 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12048 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12049 SearchForReturnInStmt(*this, Handler);
12050 }
12051}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012052
David Blaikie68f71a32013-01-18 23:03:15 +000012053bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012054 const CXXMethodDecl *Old) {
12055 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12056 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12057
12058 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12059
12060 // If the calling conventions match, everything is fine
12061 if (NewCC == OldCC)
12062 return false;
12063
Reid Kleckner78af0702013-08-27 23:08:25 +000012064 Diag(New->getLocation(),
12065 diag::err_conflicting_overriding_cc_attributes)
12066 << New->getDeclName() << New->getType() << Old->getType();
12067 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12068 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012069}
12070
Mike Stump11289f42009-09-09 15:08:12 +000012071bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012072 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000012073 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12074 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012075
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012076 if (Context.hasSameType(NewTy, OldTy) ||
12077 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012078 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012079
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012080 // Check if the return types are covariant
12081 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012082
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012083 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012084 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12085 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012086 NewClassTy = NewPT->getPointeeType();
12087 OldClassTy = OldPT->getPointeeType();
12088 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012089 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12090 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12091 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12092 NewClassTy = NewRT->getPointeeType();
12093 OldClassTy = OldRT->getPointeeType();
12094 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012095 }
12096 }
Mike Stump11289f42009-09-09 15:08:12 +000012097
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012098 // The return types aren't either both pointers or references to a class type.
12099 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012100 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012101 diag::err_different_return_type_for_overriding_virtual_function)
12102 << New->getDeclName() << NewTy << OldTy;
12103 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012104
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012105 return true;
12106 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012107
Anders Carlssone60365b2009-12-31 18:34:24 +000012108 // C++ [class.virtual]p6:
12109 // If the return type of D::f differs from the return type of B::f, the
12110 // class type in the return type of D::f shall be complete at the point of
12111 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012112 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12113 if (!RT->isBeingDefined() &&
12114 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012115 diag::err_covariant_return_incomplete,
12116 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012117 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012118 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012119
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012120 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012121 // Check if the new class derives from the old class.
12122 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12123 Diag(New->getLocation(),
12124 diag::err_covariant_return_not_derived)
12125 << New->getDeclName() << NewTy << OldTy;
12126 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12127 return true;
12128 }
Mike Stump11289f42009-09-09 15:08:12 +000012129
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012130 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012131 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012132 diag::err_covariant_return_inaccessible_base,
12133 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12134 // FIXME: Should this point to the return type?
12135 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012136 // FIXME: this note won't trigger for delayed access control
12137 // diagnostics, and it's impossible to get an undelayed error
12138 // here from access control during the original parse because
12139 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012140 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12141 return true;
12142 }
12143 }
Mike Stump11289f42009-09-09 15:08:12 +000012144
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012145 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012146 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012147 Diag(New->getLocation(),
12148 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012149 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012150 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12151 return true;
12152 };
Mike Stump11289f42009-09-09 15:08:12 +000012153
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012154
12155 // The new class type must have the same or less qualifiers as the old type.
12156 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12157 Diag(New->getLocation(),
12158 diag::err_covariant_return_type_class_type_more_qualified)
12159 << New->getDeclName() << NewTy << OldTy;
12160 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12161 return true;
12162 };
Mike Stump11289f42009-09-09 15:08:12 +000012163
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012164 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012165}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012166
Douglas Gregor21920e372009-12-01 17:24:26 +000012167/// \brief Mark the given method pure.
12168///
12169/// \param Method the method to be marked pure.
12170///
12171/// \param InitRange the source range that covers the "0" initializer.
12172bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012173 SourceLocation EndLoc = InitRange.getEnd();
12174 if (EndLoc.isValid())
12175 Method->setRangeEnd(EndLoc);
12176
Douglas Gregor21920e372009-12-01 17:24:26 +000012177 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12178 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012179 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012180 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012181
12182 if (!Method->isInvalidDecl())
12183 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12184 << Method->getDeclName() << InitRange;
12185 return true;
12186}
12187
Douglas Gregor926410d2012-02-21 02:22:07 +000012188/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012189static bool isStaticDataMember(const Decl *D) {
12190 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12191 return Var->isStaticDataMember();
12192
12193 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012194}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012195
John McCall1f4ee7b2009-12-19 09:28:58 +000012196/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12197/// an initializer for the out-of-line declaration 'Dcl'. The scope
12198/// is a fresh scope pushed for just this purpose.
12199///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012200/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12201/// static data member of class X, names should be looked up in the scope of
12202/// class X.
John McCall48871652010-08-21 09:40:31 +000012203void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012204 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012205 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012206
John McCall1f4ee7b2009-12-19 09:28:58 +000012207 // We should only get called for declarations with scope specifiers, like:
12208 // int foo::bar;
12209 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000012210 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor926410d2012-02-21 02:22:07 +000012211
12212 // If we are parsing the initializer for a static data member, push a
12213 // new expression evaluation context that is associated with this static
12214 // data member.
12215 if (isStaticDataMember(D))
12216 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012217}
12218
12219/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012220/// initializer for the out-of-line declaration 'D'.
12221void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012222 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012223 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012224
Douglas Gregor926410d2012-02-21 02:22:07 +000012225 if (isStaticDataMember(D))
12226 PopExpressionEvaluationContext();
12227
John McCall1f4ee7b2009-12-19 09:28:58 +000012228 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000012229 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012230}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012231
12232/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12233/// C++ if/switch/while/for statement.
12234/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012235DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012236 // C++ 6.4p2:
12237 // The declarator shall not specify a function or an array.
12238 // The type-specifier-seq shall not contain typedef and shall not declare a
12239 // new class or enumeration.
12240 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12241 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012242
12243 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012244 if (!Dcl)
12245 return true;
12246
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012247 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12248 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012249 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012250 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012251 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012252
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012253 return Dcl;
12254}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012255
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012256void Sema::LoadExternalVTableUses() {
12257 if (!ExternalSource)
12258 return;
12259
12260 SmallVector<ExternalVTableUse, 4> VTables;
12261 ExternalSource->ReadUsedVTables(VTables);
12262 SmallVector<VTableUse, 4> NewUses;
12263 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12264 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12265 = VTablesUsed.find(VTables[I].Record);
12266 // Even if a definition wasn't required before, it may be required now.
12267 if (Pos != VTablesUsed.end()) {
12268 if (!Pos->second && VTables[I].DefinitionRequired)
12269 Pos->second = true;
12270 continue;
12271 }
12272
12273 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12274 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12275 }
12276
12277 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12278}
12279
Douglas Gregor88d292c2010-05-13 16:44:06 +000012280void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12281 bool DefinitionRequired) {
12282 // Ignore any vtable uses in unevaluated operands or for classes that do
12283 // not have a vtable.
12284 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012285 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012286 return;
12287
Douglas Gregor88d292c2010-05-13 16:44:06 +000012288 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012289 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012290 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12291 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12292 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12293 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012294 // If we already had an entry, check to see if we are promoting this vtable
12295 // to required a definition. If so, we need to reappend to the VTableUses
12296 // list, since we may have already processed the first entry.
12297 if (DefinitionRequired && !Pos.first->second) {
12298 Pos.first->second = true;
12299 } else {
12300 // Otherwise, we can early exit.
12301 return;
12302 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012303 }
12304
12305 // Local classes need to have their virtual members marked
12306 // immediately. For all other classes, we mark their virtual members
12307 // at the end of the translation unit.
12308 if (Class->isLocalClass())
12309 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012310 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012311 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012312}
12313
Douglas Gregor88d292c2010-05-13 16:44:06 +000012314bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012315 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012316 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012317 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012318
Douglas Gregor88d292c2010-05-13 16:44:06 +000012319 // Note: The VTableUses vector could grow as a result of marking
12320 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012321 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012322 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012323 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012324 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012325 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012326 if (!Class)
12327 continue;
12328
12329 SourceLocation Loc = VTableUses[I].second;
12330
Richard Smithd3b5c9082012-07-27 04:22:15 +000012331 bool DefineVTable = true;
12332
Douglas Gregor88d292c2010-05-13 16:44:06 +000012333 // If this class has a key function, but that key function is
12334 // defined in another translation unit, we don't need to emit the
12335 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012336 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012337 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012338 // The key function is in another translation unit.
12339 DefineVTable = false;
12340 TemplateSpecializationKind TSK =
12341 KeyFunction->getTemplateSpecializationKind();
12342 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12343 TSK != TSK_ImplicitInstantiation &&
12344 "Instantiations don't have key functions");
12345 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012346 } else if (!KeyFunction) {
12347 // If we have a class with no key function that is the subject
12348 // of an explicit instantiation declaration, suppress the
12349 // vtable; it will live with the explicit instantiation
12350 // definition.
12351 bool IsExplicitInstantiationDeclaration
12352 = Class->getTemplateSpecializationKind()
12353 == TSK_ExplicitInstantiationDeclaration;
12354 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12355 REnd = Class->redecls_end();
12356 R != REnd; ++R) {
12357 TemplateSpecializationKind TSK
12358 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12359 if (TSK == TSK_ExplicitInstantiationDeclaration)
12360 IsExplicitInstantiationDeclaration = true;
12361 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12362 IsExplicitInstantiationDeclaration = false;
12363 break;
12364 }
12365 }
12366
12367 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012368 DefineVTable = false;
12369 }
12370
12371 // The exception specifications for all virtual members may be needed even
12372 // if we are not providing an authoritative form of the vtable in this TU.
12373 // We may choose to emit it available_externally anyway.
12374 if (!DefineVTable) {
12375 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12376 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012377 }
12378
12379 // Mark all of the virtual members of this class as referenced, so
12380 // that we can build a vtable. Then, tell the AST consumer that a
12381 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012382 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012383 MarkVirtualMembersReferenced(Loc, Class);
12384 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12385 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12386
12387 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012388 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012389 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012390 const FunctionDecl *KeyFunctionDef = 0;
12391 if (!KeyFunction ||
12392 (KeyFunction->hasBody(KeyFunctionDef) &&
12393 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012394 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12395 TSK_ExplicitInstantiationDefinition
12396 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12397 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012398 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012399 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012400 VTableUses.clear();
12401
Douglas Gregor97509692011-04-22 22:25:37 +000012402 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012403}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012404
Richard Smithd3b5c9082012-07-27 04:22:15 +000012405void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12406 const CXXRecordDecl *RD) {
12407 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12408 E = RD->method_end(); I != E; ++I)
12409 if ((*I)->isVirtual() && !(*I)->isPure())
12410 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12411}
12412
Rafael Espindola5b334082010-03-26 00:36:59 +000012413void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12414 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012415 // Mark all functions which will appear in RD's vtable as used.
12416 CXXFinalOverriderMap FinalOverriders;
12417 RD->getFinalOverriders(FinalOverriders);
12418 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12419 E = FinalOverriders.end();
12420 I != E; ++I) {
12421 for (OverridingMethods::const_iterator OI = I->second.begin(),
12422 OE = I->second.end();
12423 OI != OE; ++OI) {
12424 assert(OI->second.size() > 0 && "no final overrider");
12425 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012426
Richard Smith4ff9ff92012-07-07 06:59:51 +000012427 // C++ [basic.def.odr]p2:
12428 // [...] A virtual member function is used if it is not pure. [...]
12429 if (!Overrider->isPure())
12430 MarkFunctionReferenced(Loc, Overrider);
12431 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012432 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012433
12434 // Only classes that have virtual bases need a VTT.
12435 if (RD->getNumVBases() == 0)
12436 return;
12437
12438 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12439 e = RD->bases_end(); i != e; ++i) {
12440 const CXXRecordDecl *Base =
12441 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012442 if (Base->getNumVBases() == 0)
12443 continue;
12444 MarkVirtualMembersReferenced(Loc, Base);
12445 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012446}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012447
12448/// SetIvarInitializers - This routine builds initialization ASTs for the
12449/// Objective-C implementation whose ivars need be initialized.
12450void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012451 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012452 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012453 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012454 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012455 CollectIvarsToConstructOrDestruct(OID, ivars);
12456 if (ivars.empty())
12457 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012458 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012459 for (unsigned i = 0; i < ivars.size(); i++) {
12460 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012461 if (Field->isInvalidDecl())
12462 continue;
12463
Alexis Hunt1d792652011-01-08 20:30:50 +000012464 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012465 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12466 InitializationKind InitKind =
12467 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012468
12469 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12470 ExprResult MemberInit =
12471 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012472 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012473 // Note, MemberInit could actually come back empty if no initialization
12474 // is required (e.g., because it would call a trivial default constructor)
12475 if (!MemberInit.get() || MemberInit.isInvalid())
12476 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012477
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012478 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012479 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12480 SourceLocation(),
12481 MemberInit.takeAs<Expr>(),
12482 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012483 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012484
12485 // Be sure that the destructor is accessible and is marked as referenced.
12486 if (const RecordType *RecordTy
12487 = Context.getBaseElementType(Field->getType())
12488 ->getAs<RecordType>()) {
12489 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012490 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012491 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012492 CheckDestructorAccess(Field->getLocation(), Destructor,
12493 PDiag(diag::err_access_dtor_ivar)
12494 << Context.getBaseElementType(Field->getType()));
12495 }
12496 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012497 }
12498 ObjCImplementation->setIvarInitializers(Context,
12499 AllToInit.data(), AllToInit.size());
12500 }
12501}
Alexis Hunt6118d662011-05-04 05:57:24 +000012502
Alexis Hunt27a761d2011-05-04 23:29:54 +000012503static
12504void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12505 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12506 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12507 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12508 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012509 if (Ctor->isInvalidDecl())
12510 return;
12511
Richard Smith802c4b72012-08-23 06:16:52 +000012512 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12513
12514 // Target may not be determinable yet, for instance if this is a dependent
12515 // call in an uninstantiated template.
12516 if (Target) {
12517 const FunctionDecl *FNTarget = 0;
12518 (void)Target->hasBody(FNTarget);
12519 Target = const_cast<CXXConstructorDecl*>(
12520 cast_or_null<CXXConstructorDecl>(FNTarget));
12521 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012522
12523 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12524 // Avoid dereferencing a null pointer here.
12525 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12526
12527 if (!Current.insert(Canonical))
12528 return;
12529
12530 // We know that beyond here, we aren't chaining into a cycle.
12531 if (!Target || !Target->isDelegatingConstructor() ||
12532 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012533 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012534 Current.clear();
12535 // We've hit a cycle.
12536 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12537 Current.count(TCanonical)) {
12538 // If we haven't diagnosed this cycle yet, do so now.
12539 if (!Invalid.count(TCanonical)) {
12540 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012541 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012542 << Ctor;
12543
Richard Smith802c4b72012-08-23 06:16:52 +000012544 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012545 if (TCanonical != Canonical)
12546 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12547
12548 CXXConstructorDecl *C = Target;
12549 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012550 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012551 (void)C->getTargetConstructor()->hasBody(FNTarget);
12552 assert(FNTarget && "Ctor cycle through bodiless function");
12553
Richard Smith802c4b72012-08-23 06:16:52 +000012554 C = const_cast<CXXConstructorDecl*>(
12555 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012556 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12557 }
12558 }
12559
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012560 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012561 Current.clear();
12562 } else {
12563 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12564 }
12565}
12566
12567
Alexis Hunt6118d662011-05-04 05:57:24 +000012568void Sema::CheckDelegatingCtorCycles() {
12569 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12570
Douglas Gregorbae31202011-07-27 21:57:17 +000012571 for (DelegatingCtorDeclsType::iterator
12572 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012573 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012574 I != E; ++I)
12575 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012576
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012577 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12578 CE = Invalid.end();
12579 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012580 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012581}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012582
Douglas Gregor3024f072012-04-16 07:05:22 +000012583namespace {
12584 /// \brief AST visitor that finds references to the 'this' expression.
12585 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12586 Sema &S;
12587
12588 public:
12589 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12590
12591 bool VisitCXXThisExpr(CXXThisExpr *E) {
12592 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12593 << E->isImplicit();
12594 return false;
12595 }
12596 };
12597}
12598
12599bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12600 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12601 if (!TSInfo)
12602 return false;
12603
12604 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012605 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012606 if (!ProtoTL)
12607 return false;
12608
12609 // C++11 [expr.prim.general]p3:
12610 // [The expression this] shall not appear before the optional
12611 // cv-qualifier-seq and it shall not appear within the declaration of a
12612 // static member function (although its type and value category are defined
12613 // within a static member function as they are within a non-static member
12614 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012615 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012616 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012617 FindCXXThisExpr Finder(*this);
12618
12619 // If the return type came after the cv-qualifier-seq, check it now.
12620 if (Proto->hasTrailingReturn() &&
David Blaikie6adc78e2013-02-18 22:06:02 +000012621 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012622 return true;
12623
12624 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012625 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12626 return true;
12627
12628 return checkThisInStaticMemberFunctionAttributes(Method);
12629}
12630
12631bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12632 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12633 if (!TSInfo)
12634 return false;
12635
12636 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012637 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012638 if (!ProtoTL)
12639 return false;
12640
David Blaikie6adc78e2013-02-18 22:06:02 +000012641 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012642 FindCXXThisExpr Finder(*this);
12643
Douglas Gregor3024f072012-04-16 07:05:22 +000012644 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012645 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012646 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012647 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012648 case EST_DynamicNone:
12649 case EST_MSAny:
12650 case EST_None:
12651 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012652
Douglas Gregor3024f072012-04-16 07:05:22 +000012653 case EST_ComputedNoexcept:
12654 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12655 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012656
Douglas Gregor3024f072012-04-16 07:05:22 +000012657 case EST_Dynamic:
12658 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012659 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012660 E != EEnd; ++E) {
12661 if (!Finder.TraverseType(*E))
12662 return true;
12663 }
12664 break;
12665 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012666
12667 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012668}
12669
12670bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12671 FindCXXThisExpr Finder(*this);
12672
12673 // Check attributes.
12674 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12675 A != AEnd; ++A) {
12676 // FIXME: This should be emitted by tblgen.
12677 Expr *Arg = 0;
12678 ArrayRef<Expr *> Args;
12679 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12680 Arg = G->getArg();
12681 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12682 Arg = G->getArg();
12683 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12684 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12685 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12686 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12687 else if (ExclusiveLockFunctionAttr *ELF
12688 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12689 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12690 else if (SharedLockFunctionAttr *SLF
12691 = dyn_cast<SharedLockFunctionAttr>(*A))
12692 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12693 else if (ExclusiveTrylockFunctionAttr *ETLF
12694 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12695 Arg = ETLF->getSuccessValue();
12696 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12697 } else if (SharedTrylockFunctionAttr *STLF
12698 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12699 Arg = STLF->getSuccessValue();
12700 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12701 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12702 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12703 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12704 Arg = LR->getArg();
12705 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12706 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12707 else if (ExclusiveLocksRequiredAttr *ELR
12708 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12709 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12710 else if (SharedLocksRequiredAttr *SLR
12711 = dyn_cast<SharedLocksRequiredAttr>(*A))
12712 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12713
12714 if (Arg && !Finder.TraverseStmt(Arg))
12715 return true;
12716
12717 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12718 if (!Finder.TraverseStmt(Args[I]))
12719 return true;
12720 }
12721 }
12722
12723 return false;
12724}
12725
Douglas Gregor433e0532012-04-16 18:27:27 +000012726void
12727Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12728 ArrayRef<ParsedType> DynamicExceptions,
12729 ArrayRef<SourceRange> DynamicExceptionRanges,
12730 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012731 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012732 FunctionProtoType::ExtProtoInfo &EPI) {
12733 Exceptions.clear();
12734 EPI.ExceptionSpecType = EST;
12735 if (EST == EST_Dynamic) {
12736 Exceptions.reserve(DynamicExceptions.size());
12737 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12738 // FIXME: Preserve type source info.
12739 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12740
12741 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12742 collectUnexpandedParameterPacks(ET, Unexpanded);
12743 if (!Unexpanded.empty()) {
12744 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12745 UPPC_ExceptionType,
12746 Unexpanded);
12747 continue;
12748 }
12749
12750 // Check that the type is valid for an exception spec, and
12751 // drop it if not.
12752 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12753 Exceptions.push_back(ET);
12754 }
12755 EPI.NumExceptions = Exceptions.size();
12756 EPI.Exceptions = Exceptions.data();
12757 return;
12758 }
12759
12760 if (EST == EST_ComputedNoexcept) {
12761 // If an error occurred, there's no expression here.
12762 if (NoexceptExpr) {
12763 assert((NoexceptExpr->isTypeDependent() ||
12764 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12765 Context.BoolTy) &&
12766 "Parser should have made sure that the expression is boolean");
12767 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12768 EPI.ExceptionSpecType = EST_BasicNoexcept;
12769 return;
12770 }
12771
12772 if (!NoexceptExpr->isValueDependent())
12773 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012774 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012775 /*AllowFold*/ false).take();
12776 EPI.NoexceptExpr = NoexceptExpr;
12777 }
12778 return;
12779 }
12780}
12781
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012782/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12783Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12784 // Implicitly declared functions (e.g. copy constructors) are
12785 // __host__ __device__
12786 if (D->isImplicit())
12787 return CFT_HostDevice;
12788
12789 if (D->hasAttr<CUDAGlobalAttr>())
12790 return CFT_Global;
12791
12792 if (D->hasAttr<CUDADeviceAttr>()) {
12793 if (D->hasAttr<CUDAHostAttr>())
12794 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012795 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012796 }
12797
12798 return CFT_Host;
12799}
12800
12801bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12802 CUDAFunctionTarget CalleeTarget) {
12803 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12804 // Callable from the device only."
12805 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12806 return true;
12807
12808 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12809 // Callable from the host only."
12810 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12811 // Callable from the host only."
12812 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12813 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12814 return true;
12815
12816 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12817 return true;
12818
12819 return false;
12820}
John McCall5e77d762013-04-16 07:28:30 +000012821
12822/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12823///
12824MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12825 SourceLocation DeclStart,
12826 Declarator &D, Expr *BitWidth,
12827 InClassInitStyle InitStyle,
12828 AccessSpecifier AS,
12829 AttributeList *MSPropertyAttr) {
12830 IdentifierInfo *II = D.getIdentifier();
12831 if (!II) {
12832 Diag(DeclStart, diag::err_anonymous_property);
12833 return NULL;
12834 }
12835 SourceLocation Loc = D.getIdentifierLoc();
12836
12837 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12838 QualType T = TInfo->getType();
12839 if (getLangOpts().CPlusPlus) {
12840 CheckExtraCXXDefaultArguments(D);
12841
12842 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12843 UPPC_DataMemberType)) {
12844 D.setInvalidType();
12845 T = Context.IntTy;
12846 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12847 }
12848 }
12849
12850 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12851
12852 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12853 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12854 diag::err_invalid_thread)
12855 << DeclSpec::getSpecifierName(TSCS);
12856
12857 // Check to see if this name was declared as a member previously
12858 NamedDecl *PrevDecl = 0;
12859 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12860 LookupName(Previous, S);
12861 switch (Previous.getResultKind()) {
12862 case LookupResult::Found:
12863 case LookupResult::FoundUnresolvedValue:
12864 PrevDecl = Previous.getAsSingle<NamedDecl>();
12865 break;
12866
12867 case LookupResult::FoundOverloaded:
12868 PrevDecl = Previous.getRepresentativeDecl();
12869 break;
12870
12871 case LookupResult::NotFound:
12872 case LookupResult::NotFoundInCurrentInstantiation:
12873 case LookupResult::Ambiguous:
12874 break;
12875 }
12876
12877 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12878 // Maybe we will complain about the shadowed template parameter.
12879 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12880 // Just pretend that we didn't see the previous declaration.
12881 PrevDecl = 0;
12882 }
12883
12884 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12885 PrevDecl = 0;
12886
12887 SourceLocation TSSL = D.getLocStart();
12888 MSPropertyDecl *NewPD;
12889 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12890 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12891 II, T, TInfo, TSSL,
12892 Data.GetterId, Data.SetterId);
12893 ProcessDeclAttributes(TUScope, NewPD, D);
12894 NewPD->setAccess(AS);
12895
12896 if (NewPD->isInvalidDecl())
12897 Record->setInvalidDecl();
12898
12899 if (D.getDeclSpec().isModulePrivateSpecified())
12900 NewPD->setModulePrivate();
12901
12902 if (NewPD->isInvalidDecl() && PrevDecl) {
12903 // Don't introduce NewFD into scope; there's already something
12904 // with the same name in the same scope.
12905 } else if (II) {
12906 PushOnScopeChains(NewPD, S);
12907 } else
12908 Record->addDecl(NewPD);
12909
12910 return NewPD;
12911}